1. 使用 CaseIterable 获取枚举的所有 case
enum CompassDirection {
case north, south, east, west
static let allCases = [north, south, east, west]
}enum CompassDirection: CaseIterable {
case north, south, east, west
}
print("There are \(CompassDirection.allCases.count) directions.")
// Prints "There are 4 directions."
let caseList = CompassDirection.allCases
.map({ "\($0)" })
.joined(separator: ", ")
// caseList == "north, south, east, west"enum CompassDirection: CaseIterable {
case north, south, east
case west(Int)
static var allCases: [CompassDirection] {
return [north, south, east, west(0)]
}
}
print("There are \(CompassDirection.allCases.count) directions.")
// Prints "There are 4 directions."
let caseList = CompassDirection.allCases
.map({ "\($0)" })
.joined(separator: ", ")
// caseList == "north, south, east, west(0)"Last updated
Was this helpful?