Hello! This is my first post, please tell me even more so if I'm making a mess!
I came across a case where a negative integer literal can be converted to an unsigned integer type without warning, when generics are involved. I posted to StackOverflow and was directed here with my question (mostly-repost follows).
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())
$ swiftc bad.swift
$ ./bad
0
My system:
$ swift --version
swift-driver version: 1.26.21 Apple Swift version 5.5.2 (swiftlang-1300.0.47.5 clang-1300.0.29.30)
Target: arm64-apple-macosx12.0