简体   繁体   中英

How to convert Int32 to String in Swift 4?

I am having difficulty in converting an Int32 to String. I tried to following:

String(cartItem?.quantity)

"\\(cartItem?.quantity)" but no luck.

cart.quantity is of type Int32.

quantity is an attribute of cart in the CoreData model.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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