Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift, does Int have a hidden initializer that takes a String?

Tags:

swift

I tried looking at the Swift API for Int, and I'm still not sure why this works:

var foo = Int("100")

I see the following initializers in the documentation:

init()
init(_: Builtin.Word)
init(_: Double)
init(_: Float)
init(_: Int)
init(_: Int16)
init(_: Int32)
init(_: Int64)
init(_: Int8)
init(_: UInt)
init(_: UInt16)
init(_: UInt32)
init(_: UInt64)
init(_: UInt8)
init(_:radix:)
init(_builtinIntegerLiteral:)
init(bigEndian:)
init(bitPattern:)
init(integerLiteral:)
init(littleEndian:)
init(truncatingBitPattern: Int64)
init(truncatingBitPattern: UInt64)

But I don't see a init(_: String) above. Is there some automagic that happens under the hood?

like image 299
Skalley Wagg Avatar asked Oct 17 '15 10:10

Skalley Wagg


1 Answers

There is a

extension Int {
    /// Construct from an ASCII representation in the given `radix`.
    ///
    /// If `text` does not match the regular expression
    /// "[+-][0-9a-zA-Z]+", or the value it denotes in the given `radix`
    /// is not representable, the result is `nil`.
    public init?(_ text: String, radix: Int = default)
}

extension method taking a string and an optional radix (which is 10 by default):

var foo = Int("100") // Optional(100)
var bar = Int("100", radix: 2) // Optional(4)
var baz = Int("44", radix: 3) // nil

How could one find that? Using the "trick" from "Jump to definition" for methods without external parameter names, write the equivalent code

var foo = Int.init("100")
//            ^^^^

and then cmd-click on init in Xcode :)

like image 75
Martin R Avatar answered Nov 09 '22 03:11

Martin R