是否可能有多字枚举的情况,例如
enum Country: Int {
case Pakistan=1,United Arab Emirates,United Kingdom
}
我试过了:
enum Country: Int {
case Pakistan=1,"United Arab Emirates","United Kingdom"
}
没有运气:(
<stdin>:3:46: error: expected identifier after comma in enum 'case' declaration
case Pakistan=1,"United Arab Emirates","United Kingdom"
^
<stdin>:3:46: error: consecutive declarations on a line must be separated by ';'
case Pakistan=1,"United Arab Emirates","United Kingdom"
^
;
<stdin>:3:46: error: expected declaration
case Pakistan=1,"United Arab Emirates","United Kingdom"
^
<stdin>:2:15: error: an enum with no cases cannot declare a raw type
enum Country: Int {
^
<stdin>:2:6: error: type 'Country' does not conform to protocol 'RawRepresentable'
enum Country: Int {
^
Swift.RawRepresentable:9:13: note: protocol requires nested type 'RawValue'
typealias RawValue
^
答案 0 :(得分:2)
相反,请使用PascalCase。
enum Country: Int {
case Pakistan=1, UnitedArabEmirates, UnitedKingdom
}
答案 1 :(得分:2)
不,是你问题的答案。
检查Swift的语言参考: Enumeration Declaration
报告声明的语法
...
enum-case-name →identifier
...
所有枚举案例名称都需要匹配the syntax of indentifier,但空格分隔的单词(即使您尝试将它们用引号中的符号括起来)也不匹配。
如果你可以使用String
作为你的枚举的RawValue,你可以这样写:
enum Country: String {
case Pakistan, UnitedArabEmirates = "United Arab Emirates", UnitedKingdom = "United Kingdom"
}
但是,如您所见,此枚举对每个案例都缺少Int
信息,因此可能不适合您的用例。
答案 2 :(得分:1)
您不能在“案例”声明中使用“空格”,但您可以使用“得分不足”。然后你可以添加将“under score”替换为“space”的属性
enum Country: Int {
case Pakistan = 1
case United_Arab_Emirates
case United_Kingdom
var stringValue: String {
return String(self).stringByReplacingOccurrencesOfString("_", withString: " ")
}
}
然后你可以像
一样使用它 let country = Country.United_Arab_Emirates
print(country.rawValue, ":", country.stringValue)
答案 3 :(得分:1)
您实际上可以如下所示并使用这些值:
enum SuctionFrequencyTime: Int {
static let values = ["<½ Hr", "½ Hr", "Hourly", "2 Hourly", ">2 Hourly"]
case lessThanHalfHour = 1, halfHour, hourly, twoHours, greaterThanTwoHours
}
如果没有空格,则可以使用CaseIterable
来符合枚举