简体   繁体   English

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

[英]Convert Int to String in Swift and remove optional wrapping?

I am attempting to convert Int? 我正在尝试转换Int? to a String and assign it to a label without including the optional text. 字符串,并将其分配给标签,但不包括可选文本。 I currently have: 我目前有:

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"]

    }


}

In the class accessing it 在课堂上访问它

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

and the output is: Optional(1) 输出为: Optional(1)

How would I make it just output 1 and remove the optional text? 我将如何使其仅输出1并删除可选文本?

a is an Optional , so you need to unwrap it prior to applying a String by Int initializer to it. aOptional ,因此您需要先将其拆开,然后再将String by Int初始化器应用于它。 Also, b needn't really be an Optional in case you eg want to supply a default value for it for cases where a is nil . 另外,如果您想为anil情况提供默认值,则b不一定是Optional

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

Or, in case the purpose is to assign the possibly existing and possibly String -convertable value of a onto the text property of an UILabel , you could assign a successful conversion to the label using optional binding: 或者,如果目的是可能存在的,并有可能分配String的-convertable值atext的财产UILabel ,你可以使用可选的绑定指定一个转换成功的标签:

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

Why don't? 为什么不呢

let a : Int = 1
var b = "\(a)"
print(b)

so 所以

$ swift
[ 9> let a : Int = 1
a: Int = 1
[ 10> var b = "\(a)"
b: String = "1"
[ 11> print(b)
1

By the way there are other options like this one 顺便说一下,还有其他这样的选择

12> var c = a.description
c: String = "1"
 13> print(c)
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM