8

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?

Skalley Wagg
  • 105
  • 1
  • 1
  • 4

1 Answers1

8

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 :)

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Nice thanks! Do you know why this might be left out of their documentation? Are methods defined in this way special or different from those listed in the docs? – Skalley Wagg Oct 17 '15 at 16:10
  • @SkalleyWagg: Actually it is there, and you have even copied it into your question (which I did not notice until now :). It is `init(_:radix:)`. – Martin R Oct 17 '15 at 16:40
  • Ah. How is this read? I thought what follows the colon is the data type. I would've imagined it would be defined more like: `init(_:String, radix:Int)` – Skalley Wagg Oct 17 '15 at 17:37
  • @SkalleyWagg: Well yes, and that is what you see e.g. in the Xcode Quick Help. I *assume* that the import to the documentation is not optimal and not consistent. In `init(truncatingBitPattern: Int64)` the type of the parameter is given, but in `init(littleEndian:)` it is not. If you are really curious, file a bug report at Apple! – Martin R Oct 17 '15 at 17:44
  • Got it! I was just worried there was some syntax shorthand I didn't understand yet. Thank you very much for your tutelage. – Skalley Wagg Oct 17 '15 at 18:08