Int的扩展需要显式调用init

时间:2015-07-08 15:03:50

标签: swift

我正在使用自己的init创建Int的扩展,但我无法隐式使用init。有人可以解释一下原因吗?然而,我可以明确地调用init,如下所示。

extension Int {

    init?(fromHexString: String) {
        let HexRadix:Int = 16
        let DigitsString = "0123456789abcdefghijklmnopqrstuvwxyz"

        let digits = DigitsString
        var result = Int(0)
        for digit in fromHexString.lowercaseString {
            if let range = digits.rangeOfString(String(digit)) {
                let val = Int(distance(digits.startIndex, range.startIndex))
                if val >= Int(HexRadix) {
                    return nil
                }
                result = result * Int(HexRadix) + val
            } else {
                return nil
            }
        }
        self = result
    }


}

let firstString = "ff"

//This works
let parsedInt:Int = Int.init(fromHexString: firstString)!
println("\(parsedInt)")

//But this does not ; Error: Int is not identical to Int? Why??
let parsedInt1:Int = Int(fromHexString: firstString)!
println("\(parsedInt1)")

0 个答案:

没有答案