Swift: Nil 与 return 类型的字符串不兼容

Swift: Nil is incompatible with return type String

我在 Swift 中有此代码:

guard let user = username else{
        return nil
    }

但我收到以下错误:

Nil is incompatible with return type String

你们中有人知道我为什么或如何在这种情况下 return nil 吗?

非常感谢你的帮助

您的函数是否声明了可选的 return 类型?

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

查看更多信息: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.”

你必须告诉编译器你想要 return 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)
}

注意我需要如何告诉编译器我正在 return 的对象 Friend 是一个 optional Friend?.否则会报错。

*您的函数是否声明了可选的 return 类型?

func minAndmax(array:[Int])->(min:Int, max:Int)? {
    if array.isEmpty {
        return nil
    }

    var currentMin = array[0]
    var currentMax = array[0]

    for value in array {
        if value < currentMin {
            currentMin = value
        }
        else if value > currentMax {
            currentMax = value
        }
    
    }
    return (currentMin, currentMax)
}

if let bounds = minAndmax(array:  [8, -6, 2, 109, 3, 71]) {
    print(bounds)
}