Ospfranco Ospfranco - 7 months ago 15
Swift Question

Swift how to create and test an object with nil properties?

I'm trying to get my head around optionals, let's say I have the following classes:

class Contact {

var displayName:String

init(displayName:String) {
self.displayName = displayName
}

}

class Contacts {
func create(displayName:String) -> Contact {

return Contact(displayName: displayName)
}
}


as you can see the Contact class has a field displayName, but this value can be nil on initialization.

so to initialize this class I would normally do:

let contact = Contact(displayName: "Test Name")


but instead I want to be able to do this as well:

let contact = Contact()


or

let contact = Contacts().create()

Answer

You can make the init parameter an optional String?, with a default value nil:

class Contact {
    var displayName: String?

    init(displayName: String? = nil) {
        self.displayName = displayName
    }
}

let contact1 = Contact()
let contact2 = Contact(displayName: "John")

The same works for the Contacts class:

class Contacts {
    func create(displayName: String? = nil) -> Contact {
        return Contact(displayName: displayName)
    }
}

let contacts = Contacts()
let contact3 = contacts.create()
let contact4 = contacts.create("Mary")