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

前端 未结 1 1008
有刺的猬
有刺的猬 2020-12-20 17:10

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 i

相关标签:
1条回答
  • 2020-12-20 17:26

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

    0 讨论(0)
提交回复
热议问题