Search code examples
iosswiftxcode7guard

Swift: Nil is incompatible with return type String


I have this code in Swift:

guard let user = username else{
        return nil
    }

But I'm getting the following errors:

Nil is incompatible with return type String

Any of you knows why or how I return nil in this case?

I'll really appreciate your help


Solution

  • 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.