-1
public class User : NSObject {
    var id: Int //will throw an error during build
    var name: String?
    override init(){
    }
    convenience init(id: Int, name: String?){
        self.id = id
        self.name = name
    }
}

I want to create a user class. The id should non-optional. However, my above code does not work unless I change the line to:

var id: Int = 0

I don't want to do this. Is there a better way?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • You'll either have to set `id` in your `init()` or use the solution Fonix provided. Because right now, if you try: `let user = User()`, then `id` won't be initialized. – Eendje Mar 23 '16 at 03:27
  • Related reading: [Class does not implement its superclass's required members](http://stackoverflow.com/a/32108404/2792531) – nhgrif Mar 28 '16 at 23:12

2 Answers2

3

Delete the word convenience! Convenience is exactly the opposite of what you want. You want this to be a designated initializer. Like this:

public class User : NSObject {
    var id: Int
    var name: String?
    init(id: Int, name: String?){
        self.id = id
        self.name = name
        super.init()
    }
}

This forces the creator of a User to supply an id, which is exactly what you want.

matt
  • 515,959
  • 87
  • 875
  • 1,141
1
public class User {
    let id: Int
    var name: String?

    init(id: Int, name: String? = nil) {
        self.id = id
        self.name = name
    }
}

let user = User(id: 3) // works without errors

As you can see, I changed some things. You probably don't really need to subclass NSObject, and I don't think you'll want to change a user's id after initialisation, so it makes more sense to make it a let constant.

Tim Vermeulen
  • 12,352
  • 9
  • 44
  • 63
  • i dont see how you can make this assumption. i would say a struct is definitely not a good fit for a User object (in normal circumstancecs), since each time the user object is assigned, it will be copied (the nature of a struct in swift). so making changes to say `name` in one place will have no effect on the user object in another place. – Fonix Mar 23 '16 at 03:50
  • That may be so, and in that case changing `struct` to `class` would solve that problem. – Tim Vermeulen Mar 23 '16 at 03:51
  • I guess you're right a `class` makes more sense here, I updated my answer. – Tim Vermeulen Mar 23 '16 at 03:52
  • and now you havnt solved the problem with the compile time error – Fonix Mar 23 '16 at 03:52
  • There must be a reason why he's using a convenience initializer though? – Eendje Mar 23 '16 at 03:53
  • Yea, well his example is kinda basic so it's hard to tell if he really needs a convenience initializer. – Eendje Mar 23 '16 at 03:58
  • 2
    @Eendje Based on the asking history of this user, it's unlikely there's a *good* reason. – nhgrif Mar 28 '16 at 23:11