我正在尝试将Int16值转换为String,但它使用Optional赋值,并且不允许我强行打开它。
String(describing:intValue)
结果:可选(intValue)
答案 0 :(得分:4)
先打开intValue
,然后将其传递给字符串初始值设定项:String(unwrappedIntValue)
以下是处理可选项的一些方法。我已经添加了带有类型注释的显式string#
变量,以明确涉及的类型
let optionalInt: Int? = 1
// Example 1
// some case: print the value within `optionalInt` as a String
// nil case: "optionalInt was nil"
if let int = optionalInt {
let string1: String = String(int)
print(string1)
}
else {
print("optionalInt was nil")
}
// Example 2, use the nil-coalescing operator (??) to provide a default value
// some case: print the value within `optionalInt` as a String
// nil case: print the default value, 123
let string2: String = String(optionalInt ?? 123)
print(string2)
// Example 3, use Optional.map to convert optionalInt to a String only when there is a value
// some case: print the value within `optionalInt` as a String
// nil case: print `nil`
let string3: String? = optionalInt.map(String.init)
print(string3 as Any)
// Optionally, combine it with the nil-coalescing operator (??) to provide a default string value
// for when the map function encounters nil:
// some case: print the value within `optionalInt` as a String
// nil case: print the default string value "optionalInt was nil"
let string4: String = optionalInt.map(String.init) ?? "optionalInt was nil"
print(string4)
答案 1 :(得分:1)
您可以使用字符串插值将数字转换为String
:
let stringValue = "\(intValue)"
或者您可以使用标准String
初始化程序:
let stringValue = String(intValue)
如果数字是Optional
,请先打开它:
let optionalNumber: Int? = 15
if let unwrappedNumber = optionalNumber {
let stringValue = "\(unwrappedNumber)"
}
或者
if let unwrappedNumber = optionalNumber {
let stringValue = String(unwrappedNumber)
}