mercredi 6 juillet 2016

Declare instance variable in Swift : optional vs forced unwrapping vs initial value


This is a basic question about the best practice in swift to declare a swift class with instance variable, all the values will be received from Firebase callback. What is the best approach among these choices or let me know if there another better way:

Solution 1:

class User: NSObject {
    var name:String = ""

    override init() {
        super.init()
    }
}

Solution 2:

class User: NSObject {
    var name:String!

    override init() {
        super.init()
    }   
}

Solution 3:

class User: NSObject {
    var name:String?

    override init() {
        super.init()
    }   
}

Solution 4:

class User: NSObject {

    var name:String

    override init() {
        super.init()
        // Now I need to init name variable here
    } 
}

Aucun commentaire:

Enregistrer un commentaire