## Posts

Showing posts from August, 2015

### From binary to decimal values in Swift (updated Swift 3, Xcode 8)

Before we start it definitely needs to be noted that Swift has binary literals:
0b11011111 // 223 And also that you can convert a binary String to a decimal using the C standard library:
strtoul("11011111", nil, 2) // 223 Bool array as a binary representation But why should this stop the fun. So first let's begin with a Bool Array, which I've typealiased to Bit for clarity. I begin with Bool because it prevents anything but 0 and 1 (or rather true and false) being used.
typealias Bit = Bool let B1 = true let B0 = false func binaryToDecimal(binary:[Bit]) -> Int { var bitValue = 1, total = 0 for b in binary.reverse() { if b == true { total += bitValue } bitValue *= 2 } return total } binaryToDecimal([B1,B1,B0,B1,B1,B1,B1,B1]) // 223 Swift 3, Xcode 8typealias Bit = Bool let B1 = true let B0 = false func binaryToDecimal(binary:[Bit]) -> Int { var bitValue = 1, total = 0 for b in binary.reversed() { …

### Protect yourself: Retrieving penultimate values from arrays in Swift

The crashers One of the first thoughts that comes to the mind when retrieving penultimate values is to count the array and work backwards.
let values = ["2","4","6"] values[values.count - 2] // crashes if count is less than 2 values[values.endIndex.predecessor().predecessor()] // an alternative way to do the same thing, also crashes if count is less than 2 If the array contains only one element, however, the app will crash. Similarly if we reversed the array and worked forwards, an array of 1 item or less would again crash the attempt to retrieve a penultimate value.
let values = ["2","4","6"] values.reverse()[1] // crashes if count is less than 2 The reason for the crash is that, as with any array, an attempt to retrieve a value beyond its bounds the result is exactly this: a crash.
Protected but error prone One form of protection against crashes is to use advance and to ensure we don't advance beyond the bounds of t…