Operators precedence matters when we have many operators in one expression. The operator with the highest precedence will be evaluated first.
The order of the operators precedence it is different from language to language. For Swift you can find many examples here: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html
When we are reading some sudo code or code from another language we have to pay attention on the operators order. Let’s have a look on an example of the Bech32 algorithm https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
Here we can find the following method:
1 2 3 4 |
def bech32_create_checksum(hrp, data): values = bech32_hrp_expand(hrp) + data polymod = bech32_polymod(values + [0,0,0,0,0,0]) ^ 1 return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)] |
If we try to implement the same method in Swift we have to be careful with the operators precedence otherwise the algorithm will not be correct.
Instead of writing:
1 2 3 4 5 6 7 8 9 |
func checksum(hrp: String, data: [UInt8]) -> [UInt8] { let values = bech32_hrp_expand(hrp) + data let polymod = bech32_polymod(values + [0,0,0,0,0,0]) ^ 1 var result: [UInt] = [] for i in (0..<6) { result.append((polymod >> 5 * (5 - UInt(i))) & 31) } return result.map { UInt8($0) } } |
we have to write:
1 2 3 4 5 6 7 8 9 |
func checksum(hrp: String, data: [UInt8]) -> [UInt8] { let values = bech32_hrp_expand(hrp) + data let polymod = bech32_polymod(values + [0,0,0,0,0,0]) ^ 1 var result: [UInt] = [] for i in (0..<6) { result.append((polymod >> (5 * (5 - UInt(i)))) & 31) } return result.map { UInt8($0) } } |
Otherwise the algorithm is not correct!