gpt4 book ai didi

swift - 从 Swift 中的 Dictionary 中提取字符串值

转载 作者:搜寻专家 更新时间:2023-10-31 21:52:46 24 4
gpt4 key购买 nike

我只想从 Swift 中的 json 响应中提取一些字符串值,但我找不到简单的方法来完成它。

var result: Dictionary<String, AnyObject> = [ "name" : "Steve", "surname" : "Jobs"]

if let name = result["name"] {
//Warning: Constant 'name' inferred to have 'AnyObject', which may be unexpected
}

if let name = result["name"] as String {
//Error: (String, AnyObject) is not convertible to String
}

什么是正确的方法?

干杯

最佳答案

此答案最后针对 Swift 5.4 和 Xcode 12.5 进行了修订。


在 Swift 中,String 是一个结构体,而不是一个类。您需要使用 Any,而不是 AnyObject

let result: [String: Any] = ["name" : "Steve", "surname" : "Jobs"]

转换应该是可选的,使用 as? 而不是 as

if let name = result["name"] as? String {
// no error
}

关于swift - 从 Swift 中的 Dictionary<String, AnyObject> 中提取字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25108294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com