THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
An enum is a group of case statements with fixed values.
This tutorial explains the length of a Swift Enum
enum WeekEnd {
case Saturday
case Sunday
}
print(WeekEnd.count)
It throws an error main.swift:6:15: error: type 'WeekEnd' has no member 'count'
.
There is no method count in swift e
There are multiple ways to get the count of cases in a swift enumeration.
add CaseIterable
to enum and It provides an allCases
function that returns a sequence of collection of enum cases. you can call the count property to return the length of an enum.
enum WeekEnd:CaseIterable {
case Saturday
case Sunday
}
print(WeekEnd.allCases) // [main.WeekEnd.Saturday, main.WeekEnd.Sunday]
print(WeekEnd.allCases.count) // 2
Add static count method that returns Int value. Using a while loop iterates all cases and increments the count value by 1.
Here is an example
enum WeekEnd:Int {
case Saturday
case Sunday
static let count: Int = {
var max: Int = 0
while let _ = WeekEnd(rawValue: max) {
max += 1 }
return max
}()
}
print(WeekEnd.count) //2
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts