如何将 String? 类型的对象分配给 String 类型的变量? [英] How do you assign a String?-type object to a String-type variable?
问题描述
我想将字典的 value 元素分配给 String 变量.
I would like to assign the value element of a dictionary to a String variable.
在swiftUI 中,字典中的所有值元素都以String 形式返回?类型.
In swiftUI, all value elements in dictionaries are returned as String? type.
当一个字符串?type 分配给 String 变量,该 String 变量在 swiftUI 应用程序中显示为 Optional("theStringIamTryingToDisplay").
When a String? type is assigned to a String variable, the String variable displays in the swiftUI app as Optional("theStringIamTryingToDisplay").
我如何摆脱可选"在应用程序显示中?
How do I get rid of the "Optional" in the app display?
推荐答案
您必须首先确保变量实际上不包含 nil
.您可以通过多种方式做到这一点 - 可能会很好阅读:
You'll have to first make sure that the variable doesn't in fact contain nil
. You can do that in a number of ways -- might be good to read:
- Swift:为 nil 测试可选项
- https://www.hackingwithswift.com/articles/136/the-complete-guide-to-optionals-in-swift
- https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html
一种方法是通过可选绑定:
One way is by optional binding:
if let myVariable = myDictionary["key"] {
Text(myVariable)
}
另一个是提供一个默认值:
Another is to provide an default value:
Text("My result: \(myDictionary["key"] ?? "default value")
还有其他可能性,但这些以及上面的链接应该可以帮助您入门.
There are other possibilities, but these, plus the links above, should get you started.
这篇关于如何将 String? 类型的对象分配给 String 类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!