4 ms·
I code several times faster in ObjC than Swift, and this is after writing two released Swift apps. Just a simple thing like writing string to num to string tha
by w0mbat 5y ago
I code several times faster in ObjC than Swift, and this is after writing two released Swift apps.
Just a simple thing like writing string to num to string that works in different bases is a nightmare in Swift.
- bsaul 5y agothe swift string / substring api is still incredibly convoluted (or poorly documented, or both), but my feeling is that it's because it does a lot.
- fingerlocks 5y agoHope this eases your nightmares: String( Int("ff", radix: 16), radix: 10)
- w0mbat 5y agoActually that simplistic approach crashes if the value of the string goes out of range or the string contains invalid characters for the base. For commercial quality code dealing with user input you need to do your own checking char by char and assemble the result using multipliedReportingOverflow and addingReportingOverflow. The char by char processing is a pain given you can't really take the value of a Character the way you can in other languages and end up having to feed them through a map. In the end my correct bulletproof implementation is only about a page of code, but it was awkward to write.
- fingerlocks 5y agoYou yourself said "Just a simple thing like...", so I thought you were looking for a simple solution. Your complaints are no different if you were using strtol/atoi, so what's unique about swift here? Are you expecting "value of character" to be in some range that's not within 0..<radix? I have also written commercial code that does this, and I'm just going to paste it here because it's actually not that much code. Sums two strings of arbitrary length, well outside of the overflow limit, for the given base. Returns the sum as string in the base given. No mapping or overflow checks needed. Invalid characters for the base are treated as 0, but you can easily modify it to throw an error or whatever. func sumStrings(_ left: String, _ right: String, _ radix: Int) -> String { var left = Array(left) var right = Array(right) var carry = 0 var result: String = "" while left.isEmpty == false || right.isEmpty == false { let charLeft = left.popLast() ?? "0" let charRight = right.popLast() ?? "0" let intLeft = Int("\(charLeft)", radix: radix) ?? 0 let intRight = Int("\(charRight)", radix: radix) ?? 0 carry += (intLeft + intRight) result = String(carry % radix, radix: radix, uppercase: false) + result carry /= radix } if carry % radix != 0 { result = String(carry % radix, radix: radix, uppercase: false) + result } return result }