Don Giovanni
Don Giovanni

Reputation: 187

Swift 3 conversion from Int to String

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

Upvotes: 13

Views: 35181

Answers (4)

Mercedes
Mercedes

Reputation: 16

I saw this solution to somebody, thank you, to that 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")" 

Upvotes: 0

Satheesh
Satheesh

Reputation: 11276

For people who want to convert optional Integers to Strings on Swift 3,

String(describing:YourInteger ?? 0)

Upvotes: 6

Alexander
Alexander

Reputation: 63397

It's calling init(_:) (or init(_:) for UnsignedInteger) arguments of the String class.

Rather than defining separate initializers for Int, Int64, Int32, Int16, Int8, UInt, UInt64, UInt32, UInt16, and UInt8, Apple made two generic initializers: one for SignedInteger types, and one for UnsignedInteger types.

Upvotes: 12

Chuck Smith
Chuck Smith

Reputation: 2101

For anyone just looking to convert an int to string in Swift 3:

let text = "\(myInt)"

Upvotes: 35

Related Questions