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

12

我有这段Swift代码:

guard let user = username else{
        return nil
    }

但是我遇到了以下错误:

Nil is incompatible with return type String

你们中有谁知道我在这种情况下为什么会返回nil或者怎样返回nil吗?

非常感谢你们的帮助。


在Swift中,你不能返回Nil值,请将你的方法的返回类型更改为String。 - Anbu.Karthik
这可能会对你有所帮助:http://stackoverflow.com/questions/32232392/swift-casting-generic-to-optional-with-a-nil-value-causes-fatalerror - swiftBoy
请展示您的函数更多代码,即其返回类型。 - luk2302
2
@Anbu.Karthik,当返回类型是可选的时候(Optional类型实现了NilLiteralConvertible),在Swift中可以返回nil。问题在于该方法的返回类型是String。如果他想要返回nil的能力,那么返回类型应该是String?。 - Kevin
3个回答

27

20

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

注意我需要告诉编译器,我正在返回的Friend对象是一个可选的Friend?。否则它会抛出一个错误。


非常好的答案。 - Naresh
谢谢!非常感谢。 - Erik van der Neut

0

*你的函数是否声明了可选的返回类型?

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)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接