简体   繁体   English

如何在Swift 4中将Int32转换为String?

[英]How to convert Int32 to String in Swift 4?

I am having difficulty in converting an Int32 to String. 我在将Int32转换为String时遇到困难。 I tried to following: 我试图遵循:

String(cartItem?.quantity)

"\\(cartItem?.quantity)" but no luck. "\\(cartItem?.quantity)"但没有运气。

cart.quantity is of type Int32. cart.quantity的类型为Int32。

quantity is an attribute of cart in the CoreData model. 数量是CoreData模型中cart的属性。

The question isn't clear but what I think this issue boils down to is that you can't init a string with an optional value. 问题尚不清楚,但我认为这个问题归结为您无法使用可选值初始化字符串。

So either do as @matt suggested and force unwrap the cartItem 因此,要么按照@matt的建议进行操作,然后强制解开cartItem

String(cartItem!.quantity)

or supply a default value 或提供默认值

String(cartItem?.quantity ?? 0)

Of course if you need to handle the fact that you might not have a cart then it is better to do it like 当然,如果您需要处理您可能没有手推车的事实,那么最好这样做

if let cart = cartItem {
    let str = "\(cart.quantity)" //or String(cart.quantity)
    //do stuff with str
} else {
    //handle no cart state
}

you can by declare string and data 您可以通过声明字符串和数据

var arrayOf32Int: [UInt32] = [1,32,100,984,13,542]

let data = Data(bytes: arrayOf32Int, count: arrayOf32Int.count * MemoryLayout<UInt32>.stride)

let string = String(data: data, encoding: .utf32LittleEndian)!

print(string)

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

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