1

so I have a string like this 0b00001 is there a way to turn that into an Int, I tried something like this,

let string = "0b0001"
let int = Int(string)

but since there is a "b" in the string to specify that it is binary it sets int to nil.

Is there any way to turn the contents of string into an int?

1 Answers1

3

Yes. You can use BinaryInteger generic initializer but you need to drop the "0b" prefix:

init?<S>(_ text: S, radix: Int = 10) where S : StringProtocol

let str = "0b0101"
let int = Int(str.dropFirst(2), radix: 2)   // 5
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571