0

I am creating an extension of Int with my own init but I cannot use the init implicitly. Can somebody please explain why? I can however call the init explicitly as shown below.

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)")
user1369024
  • 73
  • 2
  • 6
  • Could you add the missing definitions (e.g. of `DigitsString`) so that the example compiles? – Airspeed Velocity Jul 08 '15 at 15:19
  • let HexRadix:Int = 16 let DigitsString = "0123456789abcdefghijklmnopqrstuvwxyz" – user1369024 Jul 08 '15 at 15:20
  • Working like a charm in playground – Zell B. Jul 08 '15 at 15:23
  • Which version of Xcode are you running? Seems to work OK for me – Airspeed Velocity Jul 08 '15 at 15:29
  • Playground sometimes does not play well :). Please put in a swift file and compile. – user1369024 Jul 08 '15 at 15:34
  • Wait - so you are writing an extension to Int whose operation depends upon the definition of two constants _outside_ the extension? That makes no sense. Put the two `let` statements inside the initializer. – matt Jul 08 '15 at 15:41
  • Works fine from a command-line also. I don’t have your exact same Xcode, but if it’s a bug, it’s fixed in 2.0 so no point filing anything. – Airspeed Velocity Jul 08 '15 at 15:43
  • Matt, Thank You...that makes sense. – user1369024 Jul 08 '15 at 15:50
  • P.S. `find` (or `indexOf` in 2.0) into an array of digits would probably be a better fit than `rangeOfString`: `extension Int { init?(fromHexString: String) { let digits = Array("0123456789abcdef");self = 0;for digit in fromHexString.lowercaseString { if let val = find(digits, digit) { self = self << 4 + val } else { return nil } } } }` – Airspeed Velocity Jul 08 '15 at 15:51
  • Your (edited) code compiles and runs without problems in Xcode 6.4, so what is your question now? – Btw, your code looks similar to this one http://stackoverflow.com/a/27190430/1187415 :) – Martin R Jul 08 '15 at 17:26
  • Unfortunately it does not for me with 6.4. StackOverflow does not allow me to put a screenshot unfortunately.. – user1369024 Jul 08 '15 at 18:46

0 Answers0