bastie
(Sebastian Ritter)
1
Hello!
Maybe not the best category, perhaps not too bad category?
I like the following ONE-Step Code for fast hack an idea:
let _ = UInt8 (128+128)
It is a nice hack for later add a better error handling. But if this works, why are the compiler so foolish and work not with
let _ = UInt8 (128) + UInt8 (128)
Arithmetic operation '128 + 128' (on type 'UInt8') results in an overflow
Yes same as first.
I did not like the following TWO-Step Code, to call a given function like this:
func callMeIfYouCan (p1 : UInt8, p2 : [UInt8], p3 : (t1 : UInt8, t2 : UInt8)?) -> Bool
If you mean Swift can detect optional itself - no! So I need this
let t : (UInt8,UInt8) = (0,0)
let oT : (UInt8,UInt8)? = t
let _ = callMeIfYouCan (p1: 0, p2: [0], p3: oT)
Not working is
let t : (UInt8,UInt8) = (0,0)
let _ = callMeIfYouCan (p1: 0, p2: [0], p3: t)
Is it really better, cleaner code to create a constant oT only for using as param?
with regards
Sebastian
An integer literal is an Int
unless you use as
.
_ = 128 as UInt8 + 128
Conversion with initializers, on the contrary, is done at runtime.
You forgot [ ]
.
_ = callMeIfYouCan(p1: 0, p2: [0], p3: (0, 0))
Alejandro
(Alejandro Alonso)
3
This isn't quite true since https://github.com/apple/swift-evolution/blob/main/proposals/0213-literal-init-via-coercion.md.
// These are all the same
let x = UInt8(128)
let y: UInt8 = 128
let z = 128 as UInt8
which makes sense why the following is a compilation error
let x = UInt8(128) + UInt8(128)
because the compiler treats the literals as UInt8
s. The example where they did
let x = UInt8(128 + 128)
actually does treat the literals as Int
s and goes through the runtime initializer (which is why there is no compiler error).
4 Likes
bastie
(Sebastian Ritter)
4
missing? oh yes, but the error is at the optional. I changed this.
bastie
(Sebastian Ritter)
5
I see now XCode accept
let _ = UInt8(128+128)
but Playgrounds at iPad tell me
Not enought bits to represent the passed value.
IMHO the Compiler on all platforms must optimize constant expression 128+128 to 256 and after this step tell me this error.