在Swift中,Int有一个隐藏的初始化器,它接受一个字符串吗?

时间:2015-10-17 10:27:58

标签: swift

我尝试查看用于Int的Swift API,我仍然不确定为什么会这样:

var foo = Int("100")

我在文档中看到了以下初始化程序:

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)

但我上面没看到init(_: String)。是否有一些自动化发生在引擎盖下?

1 个答案:

答案 0 :(得分:7)

有一个

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

扩展方法取一个字符串和一个可选的基数(默认为10):

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

怎么能找到?使用"技巧"从 "Jump to definition" for methods without external parameter names,写出等价物 代码

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

然后 cmd - 点击Xcode中的init:)