展开可选值

-2 ios swift

我从服务器获取JSON数据.

这是我的代码:

let myPTYPEIntegerValue : NSInteger? = (allData as! NSDictionary ).value(forKey: "PTYPE") as? NSInteger
    if myPTYPEIntegerValue != nil{
        help.myPTYPE = String.init(describing: myPTYPEIntegerValue)
    }

    let myIdIntegerValue : NSInteger? = (allData as! NSDictionary ).value(forKey: "ID") as? NSInteger
    if myIdIntegerValue != nil{
        help.myId = String.init(describing: myIdIntegerValue)
    }                        

    let jsonIDIntegerValue : NSInteger? = (allData as! NSDictionary ).value(forKey: "UID") as? NSInteger
    if jsonIDIntegerValue != nil{
         help.myUID = String.init(describing: jsonIDIntegerValue!)
         print(help.myUID)
    }
Run Code Online (Sandbox Code Playgroud)

但它正在显示

Optional(3)
Optional(2930)
Optional(238)
Run Code Online (Sandbox Code Playgroud)

如何在这里打开可选项?我的代码有什么问题?

nil*_*ils 6

您可以使用可选绑定来解包可选:

if let jsonIDIntegerValue = jsonIDIntegerValue {
    // jsonIDIntegerValue is now a non-optional local constant
    help.myUID = String(jsonIDIntegerValue)
    print(help.myUID)
}
Run Code Online (Sandbox Code Playgroud)

这消除了对力展开的需要.有关更多信息,请参阅Swift指南(查看Optional Binding部分).

  • 到目前为止,这是最好的答案.它展示了如何正确地解包Optional,并删除了`String(describe :)的错误用法.做得好. (2认同)