3

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
6
  • 2
    This is an excellent question — and looks like a bug to me. The IntegerLiteralType of UInt32 is UInt32, so theoretically, the compiler should be able to confirm that T.IntegerLiteralType could 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.) Commented Mar 12, 2022 at 0:11
  • 2
    BTW, you're more likely to get a better and more authoritative answer over on forums.swift.org, where some of the compiler engineers could look into why this happens. Commented Mar 12, 2022 at 0:12
  • 2
    Also FWIW, this bypasses all literal checks. e.g., you can write a similar function returning 1234 and call it with Bad<UInt8>; you'll also get 0. Commented Mar 12, 2022 at 0:14
  • Thanks for the pointers! swiftc bad.swift && ./bad does not print anything other than 0. 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 -1 with ~0 fixed the "wrong" results. I'll open a thread on forums.swift.org. Commented Mar 12, 2022 at 8:38
  • 1
    Post on forums.swift.org: forums.swift.org/t/… Commented Mar 12, 2022 at 9:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.