Swift 2 missing ASCII character literals for raw value enums
| Originator: | chaos42 | ||
| Number: | rdar://21716313 | Date Originated: | 07-Jul-2015 05:35 PM |
| Status: | Open | Resolved: | |
| Product: | Devloper Tools | Product Version: | 7.0 beta (7A121l) |
| Classification: | UI/Usability | Reproducible: | Always |
Summary:
Apologies for the narrative form of this summary, but I can't come up with a better way to phrase it.
My application is parsing a binary file format. Certain data structures in this file include a one byte tag, which can take one of a small number (approx. 9) values. This seems like the perfect use of a Swift enum. Great, let's do it:
enum Tag : ... {...}
}
According to the documentation, all these single-byte values are ASCII characters. All right, let's make Tag a Character, and set the first value.
enum Tag : Character { Byte = "B" }
Testing the size of the Tag with
sizeof(Tag.RawValue.self)
reveals that this enum is 9 bytes! That's huge! And we don't have 9 bytes of data to read in anyway, since our field is 1 byte. So let's make it a UInt8 instead:
enum Tag: UInt8 {Byte = "B"}
error: "'String' is not convertible to 'UInt8'"
All right, let's try a character literal B
enum Tag: UInt8 {Byte = 'B'}
error: invalid character in source file.
To make a long story short, there appears to be no way to work around this such that the B appears anywhere in the source code (except in a comment). The only way to make this work is to use
enum Tag: UInt8 { Byte = 0x42} // or 66
This is not acceptable from a language that purports to be a general purpose programming language, usable for systems programming in particular.
Steps to Reproduce:
1. Install Xcode 7b2
2. Create a new playground.
3. Paste the following code:
enum Tag : UInt8 {
case Byte = 'B'
case Char = 'C'
case Double = 'D'
}
enum Tag2 : UInt8 {
case Byte = "B"
case Char = "C"
case Double = "D"
}
enum Tag3 : UInt8 {
case Byte = UInt8(ascii:"B")
case Char = UInt8(ascii:"C")
case Double = UInt8(ascii:"D")
}
Expected Results:
At least one of the enums should successfully compile. I don't really care which one, but as it is, the only ones that will compile are:
enum Tag4 : UInt8 {
case Byte = 0x42
case Char = 0x43
case Double = 0x44
}
enum Tag5 : UInt8 {
case Byte = 66
case Char = 67
case Double = 68
}
Actual Results:
Tag:
error: invalid character in source file.
Tag2:
error: String is not convertible to 'UInt8'
Tag3:
error: Raw value for enum case must be a literal
Version:
Version 7.0 beta (7A121l)
OS X 10.10.4 (14E46)
Notes:
Configuration:
Attachments:
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!