Swift:Nil与返回类型String不兼容

use*_*482 7 guard ios swift xcode7

我在Swift中有这个代码:

guard let user = username else{
        return nil
    }
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

Nil is incompatible with return type String
Run Code Online (Sandbox Code Playgroud)

在这种情况下,你们中的任何人都知道为什么或如何返回nil?

我真的很感谢你的帮助

小智 24

你的函数声明了一个可选的返回类型吗?

func foo() - >字符串?{...

有关详细信息,请访问:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

注意

选项的概念在C或Objective-C中不存在.Objective-C中最接近的是能够从否则返回对象的方法返回nil,nil意味着"缺少有效对象".


Jos*_*ber 8

你必须告诉编译器你要返回nil.那你怎么样?通过分配'?' 在你的对象之后.比如看看这段代码:

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)
}
Run Code Online (Sandbox Code Playgroud)

请注意,我必须告诉编译器我正在返回的对象朋友是一个可选的'朋友?' 另一方面,它给我带来了错误