【问题标题】:Swift NSObject property is not optional , but it prints optional [duplicate]Swift NSObject 属性不是 optional ,但它打印 optional [重复]
【发布时间】:2017-04-05 05:10:16
【问题描述】:
let allPlaces = resultsArray.map({ (param) -> Places in
                        return Places(dictionary: param )
                    })
                    print("All Places \(allPlaces[0].placeName)")

以上代码的输出为:

所有地方可选(“地铁”)

在下面的代码中,var 不是可选的。但是 print 语句将其打印为可选。它不应该打印All Places "Subway"吗?

class Places: NSObject {


    var name:String!


    init(dictionary:Dictionary<String, Any>) {

        name = dictionary["name"] as? String
    }
}

【问题讨论】:

  • 从这个地方字典["name"] 为?字符串它是可选的。将其更改为字典 [“名称”] 为!字符串会给你非可选的
  • 试试这个print("All Places " + allPlaces[0].placeName)
  • dictionary["name"] as? String 使其成为可选值。
  • Swift 3 incorrect string interpolation with implicitly unwrapped Optionals——一个IUO被视为一个强可选,只要它可以被类型检查为一个。
  • 当你把!?放在一个“类型”前面时,它实际上是一个Optional类型。唯一的区别是您告诉编译器,当您读取 name 属性时,您不想处理它的可空性(因为您确定它永远不会是 nil),但它仍然可能是nil。说到这里,你可以简单地将属性定义为var name:String

标签: ios swift forced-unwrapping


【解决方案1】:
var name:String!

您已将 name 声明为隐式展开的可选。从Swift 3 开始,只有在需要在本地进行类型检查时才会强制解包。否则,它只会被视为普通可选。

 print("All Places \(allPlaces[0].name)")

这里不涉及类型检查,所以 name 仍然是可选的。

如果你喜欢

let name:String = allPlaces[0].name
print("All Places \(name)")   

输出将是“所有地方地铁”

或者你需要强制打开它

 print("All Places \(allPlaces[0].name!)")

如果name 为 nil,这将导致崩溃,您应该注意它。如果有可能 name 可以为 nil,则使用 var name: String? 以便编译器强制您显式解包。

【讨论】:

    【解决方案2】:

    改成'as?' 'as!'。

    • 感叹号表示绝对清楚。

    • 问号表示可选绑定。

    [来源]

    class Places: NSObject {
    
    
        var name:String!
    
    
        init(dictionary:Dictionary<String, Any>) {
    
            name = dictionary["name"] as! String 
    
        }
    }
    

    另一种方式

    print("All Places \(allPlaces[0].placeName)")
    

    print("All Places \(allPlaces[0].placeName!)")
    
    or
    
    print("All Places \(allPlaces[0].placeName ?? "")")
    

    【讨论】:

    • 下面的答案@theodore cha 有什么区别
    • 如果“name”键不可用怎么办?
    • @andyPaul 我认为.. 使用双问号(设置默认值)// name = dictionary["name"] as?细绳 ?? ""
    • @andyPaul 双问号:如果值不可用,则保存默认值(“”)
    • @VinodKumar 我添加了其他方式。
    猜你喜欢
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2019-07-29
    相关资源
    最近更新 更多