In this simple piece of code, I'm using the integer literal -1 in a context where a value of type T is expected. T conforms to FixedWidthInteger so it's unknown at compile time whether the literal can be converted to the actual type T. If T is set to an unsigned integer type, the -1 simply becomes a 0. I would have expected a runtime error, or at least a warning at compile time. Is this a bug or is this documented somewhere?
struct Bad<T: FixedWidthInteger> {
func getNegativeOne() -> T {
return -1
}
}
print(Bad<UInt32>().getNegativeOne())
When running it from the swift repl:
$ swift
Welcome to Swift version 5.5.2-dev.
Type :help for assistance.
1> [paste code]
0
IntegerLiteralTypeofUInt32isUInt32, so theoretically, the compiler should be able to confirm thatT.IntegerLiteralTypecould represent-1; it seems that this is bypassed. What do you see when you compile the above code, outside of the repl? (The repl, like Playgrounds, sometimes exhibits different behavior, and stifles certain errors.)1234and call it withBad<UInt8>; you'll also get 0.swiftc bad.swift && ./baddoes not print anything other than0. I'm not seeing a warning or anything. This happened to me in a SwiftPM project I was working on with Xcode 13.2.1, deep within some bit-twiddling code, no warning in the editor either. Replacing-1with~0fixed the "wrong" results. I'll open a thread on forums.swift.org.