Swift: Nil is incompatible with return type String

user2924482 picture user2924482 · Nov 13, 2015 · Viewed 17.9k times · Source

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

Answer

Andrei Nagy picture Andrei Nagy · Nov 13, 2015

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