Convert Swift 3 from Int to String

In Swift 3, the String structure does not seem to have an init(_: Int) initializer that will convert from Int to String . My question is: why does let i = String(3) ? Which String method or initializer does it call? Thanks.

+8
string swift3
source share
4 answers

It calls the init(_:) (or init(_:) for UnsignedInteger ) arguments of the String class.

Instead of defining separate initializers for Int , Int64 , Int32 , Int16 , Int8 , UInt , UInt64 , UInt32 , UInt16 and UInt8 , Apple has developed two generic initializers: one for SignedInteger types and one for UnsignedInteger types.

+9
source share

For anyone who wants to convert int to string in Swift 3:

 let text = "\(myInt)" 
+29
source share

For people who want to convert optional integers to strings in Swift 3,

 String(describing:YourInteger ?? 0) 
+5
source share

I saw this solution to someone, thanks, to this person, I don’t remember who.

 infix operator ???: NilCoalescingPrecedence public func ???<T>(optional: T?, defaultValue: @autoclosure () -> String) -> String { switch optional { case let value?: return String(describing: value) case nil: return defaultValue() } } 

For example:

 let text = "\(yourInteger ??? "0")" 
0
source share

All Articles