In Swift, int has a hidden initializer that takes a string?

I tried to take a look at the Swift API for Int, and I'm still not sure why this works:

var foo = Int("100")

In the documentation, I see the following initializers:

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 do not see init(_: String)above. Is there any automation that happens under the hood?

+4
source share
1 answer

Exists

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 radius (the default is 10):

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

How can I find this? Using the "trick" from "Go to Definition" for methods without external parameter names , write the equivalent code

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

and then cmd-click on initin Xcode :)

+6
source

Source: https://habr.com/ru/post/1612037/


All Articles