tomasbasham tomasbasham - 25 days ago 8
iOS Question

Immutable class accessors in swift 3

I am trying to implement objects similar to

CNContact
and
CNMutableContact
such that I can retrieve my immutable objects from a custom store and make editions only to mutable copies of the objects.

To tackle this I have taken a look at the
CNContact
source available through Xcode to find this:

open class CNContact : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {


/*! The identifier is unique among contacts on the device. It can be saved and used for fetching contacts next application launch. */
open var identifier: String { get }


open var contactType: CNContactType { get }

...

}


However when I try something similar I get an error:

class MyModel: NSObject, NSCoding, NSSecureCoding {

// MARK: - Properties

var name: String { get }

...
}


The error being
Expected '{' to start a getter definition
. What am I doing wrong here?

The next step then would be to have a mutable subclass, very similar to
CNMutableContact
which would looks like this:

class MutableMyModel: MyModel {

// MARK: - Properties

var name: String

...
}


If my approach to this problem is sensible then why am I seeing this syntax error, and why is it valid within the Apple written code but not my own?

Finally am I going to hit any issues within my subclass where I am essentially redefining the name property?

Answer

var name: String { get } is only a definition in the protocol. A conforming class, such as MyModel needs to implement the definition, like so:

class MyModel: NSObject, NSCoding, NSSecureCoding {

    var name: String { return "String Value here" }
}