gpt4 book ai didi

swift - 在 Swift 中将 Int 转换为 String 并删除可选包装?

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:54 24 4
gpt4 key购买 nike

我正在尝试将 Int? 转换为字符串并将其分配给标签而不包括可选文本。我目前有:

struct Choice: Mappable{

var id: String?
var choice: String?
var questionId: String?
var correct: Bool?
var responses: Int?


init?(map: Map) {

}


mutating func mapping(map: Map) {
id <- map["id"]
questionId <- map["questionId"]
choice <- map["choice"]
correct <- map["correct"]
responses <- map["responses"]

}


}

在访问它的类中

var a:String? = String(describing: self.currentResult.choices?[0].responses)
print("\(a!)")

输出是:可选(1)

我如何让它只输出 1 并删除可选文本?

最佳答案

a 是一个 Optional,因此您需要在通过 Int 初始化程序应用 String 之前解包它给它。此外,b 不必真的是 Optional,以防你想为 anil 的情况提供默认值。

let a: Int? = 1
let b = a.map(String.init) ?? "" // "" defaultvalue in case 'a' is nil

或者,如果目的是将 a 的可能存在且可能是 String 的可转换值分配给 an 的 text 属性UILabel,您可以使用可选绑定(bind)将成功的转换分配给标签:

let a: Int? = 1
if let newLabelText = a.map(String.init) {
self.label.text = newLabelText
}

关于swift - 在 Swift 中将 Int 转换为 String 并删除可选包装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47165711/

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