【问题标题】:Swift: Nil is incompatible with return type StringSwift:Nil 与返回类型 String 不兼容
【发布时间】:2016-02-14 16:39:45
【问题描述】:

我在 Swift 中有这段代码:

guard let user = username else{
        return nil
    }

但我收到以下错误:

Nil is incompatible with return type String

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

非常感谢您的帮助

【问题讨论】:

  • 你不能在swift中返回Nil值,在你的方法中改变你的返回类型字符串
  • 显示你的函数的更多代码,即它的返回类型。
  • @Anbu.Karthik 当返回类型为可选时,您可以快速返回 nil(Optional 类型实现 NilLiteralConvertible)。问题是该方法的返回类型是字符串。如果他想要返回 nil 的能力,那么返回类型应该是 String?

标签: ios swift xcode7 guard


【解决方案1】:

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

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

查看更多信息:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

注意

C 或 Objective-C 中不存在可选项的概念。这 Objective-C 中最接近的事情是能够从 a 返回 nil 否则将返回对象的方法,nil 表示“ 没有有效的对象。”

【讨论】:

    【解决方案2】:

    你必须告诉编译器你想返回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?。否则会报错。

    【讨论】:

    • 非常好的答案。
    • 谢谢!非常感谢。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-08-29
      • 2016-05-28
      • 2019-09-06
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 2022-06-19
      • 1970-01-01
      • 2020-08-13
      相关资源
      最近更新 更多