You have to tell the compiler that you want to return nil
. How do you that? By assigning ?
after your object. For instance, take a look at this code:
func newFriend(friendDictionary: [String : String]) -> Friend? {
guard let name = friendDictionary["name"], let age = friendDictionary["age"] else {
return nil
}
let address = friendDictionary["address"]
return Friend(name: name, age: age, address: address)
}
Notice how I needed to tell the compiler that my object Friend
, which I'm returning, is an optional Friend?
. Otherwise it will throw an error.