2014-11-09 38 views

回答

3

如前所述here,您可以使用標準庫函數strtoul將():

let base36 = "1ARZ" 
let number = strtoul(base36, nil, 36) 
println(number) // Output: 60623 

第三個參數爲基數。有關函數如何處理空白和其他細節,請參見man page

-1

斯威夫特方式:

"123".toInt() // Return an optional 

Ç方式:

atol("1232") 

或者使用的NSString的integerValue方法

("123" as NSString).integerValue 
0

這裏是斯威夫特parseLong()。請注意,該函數返回一個Int?(可選Int),必須打開才能使用。

// Function to convert a String to an Int?. It returns nil 
// if the string contains characters that are not valid digits 
// in the base or if the number is too big to fit in an Int. 

func parseLong(string: String, base: Int) -> Int? { 
    let digits = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ") 

    var number = 0 
    for char in string.uppercaseString { 
     if let digit = find(digits, char) { 
      if digit < base { 
       // Compute the value of the number so far 
       // allowing for overflow 
       let newnumber = number &* base &+ digit 

       // Check for overflow and return nil if 
       // it did overflow 
       if newnumber < number { 
        return nil 
       } 
       number = newnumber 
      } else { 
       // Invalid digit for the base 
       return nil 
      } 
     } else { 
      // Invalid character not in digits 
      return nil 
     } 
    } 
    return number 
} 

if let result = parseLong("1110", 2) { 
    println("1110 in base 2 is \(result)") // "1110 in base 2 is 14" 
} 

if let result = parseLong("ZZ", 36) { 
    println("ZZ in base 36 is \(result)") // "ZZ in base 36 is 1295" 
} 
+0

感謝您的回答!但是我發現了一個標準庫函數strtoul()來實現這種情況 – 2014-11-10 14:22:55