Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 558
user2924482 Avatar asked Nov 13 '15 06:11

user2924482


2 Answers

Does your function declare an optional return type?

func foo() -> String? { ...

See more on: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

NOTE

The concept of optionals doesn’t exist in C or Objective-C. The nearest thing in Objective-C is the ability to return nil from a method that would otherwise return an object, with nil meaning “the absence of a valid object.”

like image 57
Andrei Nagy Avatar answered Sep 30 '22 13:09

Andrei Nagy


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.

like image 32
Josue Gisber Avatar answered Sep 30 '22 12:09

Josue Gisber