Swift: Nil is incompatible with return type String

删除回忆录丶 提交于 2019-12-30 06:36:14

问题


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


回答1:


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 that i had to tell the compiler that my Object Friend that i'm returning is an optional 'Friend?' other wise it spill an error on me




回答2:


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



来源:https://stackoverflow.com/questions/33686976/swift-nil-is-incompatible-with-return-type-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!