ios - Swift NSObject 属性不是可选的,但它打印可选

标签 ios swift forced-unwrapping

let allPlaces = resultsArray.map({ (param) -> Places in
                        return Places(dictionary: param )
                    })
                    print("All Places \(allPlaces[0].placeName)")

上述代码的输出为:

All Places Optional("Subway")

在下面的代码中,var 不是可选的。但 print 语句将其打印为可选。它不应该打印所有地方“地铁”吗?

class Places: NSObject {


    var name:String!


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

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

最佳答案

var name:String!

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

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

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

如果你喜欢

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

输出将为“All Places Subway”

或者你需要强制打开它

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

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

关于ios - Swift NSObject 属性不是可选的,但它打印可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43222287/

相关文章:

Swift View Controller 声明返回 nil

iPhone:多项选择题 - 如何避免触及两个或更多答案?

ios - 重叠访问 "result",但修改需要独占访问;考虑复制到 Xcode 10 中的局部变量

ios - dequeueReusableCell(indexPath: IndexPath 的 withIdentifier 标识符 : String,)在每次调用时返回 2 个不同的单元格

swift - 将文本字段值分配给 Swift 中的变量

Swift4:强制转换从 'Data?' 到 'Data' 只解包选项;你是想使用 '!' 吗?

ios - 如何通过 Objective C 中的类别类中的参数解析方法调用?

ios - iPhone X 顶部栏问题

ios - 应用程序在 UIActivityViewController 上崩溃

swift - 为什么在 Swift 中两个不同的数组字面量彼此相等?