gpt4 book ai didi

swift - Switft Dictionary 问题 'String?' is not convertible to 'String' ;您的意思是使用 'as!' 强制向下转换吗?

转载 作者:行者123 更新时间:2023-11-28 09:48:53 26 4
gpt4 key购买 nike

我是 Swift 和 ObjC 的新手,无法让这段简单的代码发挥作用。我收到错误“字符串?”不可转换为“字符串”;你是不是想用 'as!'强制垂头丧气?

    guard let data = context as? Dictionary<String,String> else {return}

var str : String

str = data["Score"] as String //<<<I get the error here

当我把它改成as!我知道收到此警告:Forced cast from 'String?' to 'String' 只解包选项;您是要使用“!”吗?

有什么想法可以从字典中提取字符串以便我可以使用它吗?

最佳答案

您的字典中可能没有设置键“Score”,可能会返回 nil。使用此代码解包可选:

if let score = data["Score"] {
str = score
}

因为你已经打开了 contextDictionary<String, String> , Swift 会自动推断出 score 的类型作为字符串。

关于swift - Switft Dictionary 问题 'String?' is not convertible to 'String' ;您的意思是使用 'as!' 强制向下转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53628285/

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