I'm encountering a problem with using both + and * static functions in a Swift extension. I just want + to be * and * to be +. When I use just the + operator, it works fine, but when I include both operators, I run into an infinite loop.
Works fine
extension Int {
static func + (left: Int, right: Int) -> Int {
return (left * right)
}
}
// 12
print(3 + 4)
// 12
print(3 * 4)
Now is going into an infinite loop
extension Int {
static func + (left: Int, right: Int) -> Int {
return (left * right)
}
static func * (left: Int, right: Int) -> Int {
return (left + right)
}
}
print(3 + 4)
print(3 * 4)
Any suggestions would be appreciated.
Cool trick for debugging use print(#function), see below in comments.
So here was the thing that I was looking for:
import Foundation
extension Int {
static func + (left: Int, right: Int) -> Int {
return (left &* right)
}
static func * (left: Int, right: Int) -> Int {
return (left &+ right)
}
}
// 12
print(3 + 4)
// 7
print(3 * 4)
"In Swift, the &+, &-, and &* operators provide arithmetic operations that don't trap on overflow but instead wrap around using two's complement representation. This simulates how many lower-level languages (like C) handle arithmetic overflow and how hardware instructions for arithmetic operations work."
I have no clue whatever the above explanation means, if some1 can explain this in details that would be great. I know that &* is overflow-safe multiplication but what it does, and how it is used by swift I do not know. Thanks (just comment under this answer).
Check this video Fast Conversion From Cpp Floating Point Numbers - Cassio Neri - C++Now 2024 good stuff in there. Maybe somehow this works like that, If some1 could elaborate on this thing that would be amazing.
Some additional info: Overflow Operators, and this also Table of 4-bit Binary System With the TWOs Complement Method