美文网首页
swift 字典取值 Optional Binding

swift 字典取值 Optional Binding

作者: tech_go | 来源:发表于2023-04-03 10:21 被阅读0次

self.count = response?["totalCount"] as? Int
这样写可能会导致程序崩溃。
如果response字典中没有totalCount键或者该键对应的值不是整数类型,
强制转换就会失败并抛出异常,
导致程序崩溃。

建议使用可选绑定(Optional Binding)来确保安全获取totalCount的值,例如:

if let totalCount = response["totalCount"] as? Int {
    // 使用totalCount的值
    self.count = totalCount
} else {
    // totalCount不存在或者不是整数类型
    self.count = 0
}

相关文章

网友评论

      本文标题:swift 字典取值 Optional Binding

      本文链接:https://www.haomeiwen.com/subject/bdmdddtx.html