Swift: sort array by more than 2 possible values - swift

I have an object like this:
enum State {
case starting
case inProgress
case done
}
struct MyData {
var state: State
}
var array: [MyData]
Now I want to sort array to have the starting items first, then the inProgress ones and then the done ones. How can I do so?
Thanks for your help.

Try this (playground code)
enum State: Int {
case starting
case inProgress
case done
}
struct MyData {
var state: State
}
let myData1 = MyData(state: .inProgress)
let myData2 = MyData(state: .done)
let myData3 = MyData(state: .starting)
let myData4 = MyData(state: .starting)
let myData5 = MyData(state: .inProgress)
var array = [myData1, myData2, myData3, myData4, myData5]
var sortedArray = array.sorted() { $0.state.rawValue < $1.state.rawValue }
print(sortedArray)
This approach uses the rawValue int of the enum to sort the items. I get the expected output from the print statement above.

A possible way of doing it.
Make State conform to Comparable
enum State: Int, Comparable {
case starting = 0
case inProgress = 1
case done = 2
static func <(lhs: State, rhs: State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
Sort it using state
let elms: [MyData] = ...
let sorted = elms.sorted { $0.state < $1.state }

Related

Custom comparator for Swift

This is my code (simplified code):
struct SomeStruct {
let id: Int
let age: Int
}
extension SomeStruct: Hashable {
var hashValue: Int {
return id.hashValue * age.hashValue
}
static func ==(lhs: SomeStruct, rhs: SomeStruct) -> Bool {
return lhs.id == rhs.id && lhs.age == rhs.age
}
}
struct Calculator {
let struct1: [SomeStruct]
let struct2: [SomeStruct]
func uniqueById() {
let struct3 = Set(struct2).union(Set(struct1))
// I want to union it by property 'id' only.
// If the property 'id' is equal for both objects,
// the object in struct2 should be used (since that can have a different age property)
}
}
SomeStruct is a generated struct which I do not want to edit. I want to create a Set for SomeStruct that is based on 1 property: id. For that, I think I need a custom Comparator, just as Java has. Is there any Swifty way? This is the only thing I can come up with, but I am wondering if there is a better way:
struct SomeStructComparatorById: Hashable {
let someStruct: SomeStruct
var hashValue: Int {
return someStruct.id.hashValue
}
static func ==(lhs: SomeStructComparatorById, rhs: SomeStructComparatorById) -> Bool {
return lhs.someStruct.id == rhs.someStruct.id
}
}
First, I don't think this would work in Java. addAll() doesn't take a Comparator (nor does contains, etc.) Comparators are for sorting, not equality. Conceptually this is breaking how Set works in any language. Two items are not "equal" unless they can be swapped in all cases.
That tells us that we don't want a Set here. What you want here is uniqueness based on some key. That's a Dictionary (as Daniel discusses).
You could either just have a "id -> age" dictionary or "id -> struct-of-other-properties" dictionary as your primary data type (rather than using Array). Or you can turn your Array into a temporary Dictionary like this:
extension Dictionary {
init<S>(_ values: S, uniquelyKeyedBy keyPath: KeyPath<S.Element, Key>)
where S : Sequence, S.Element == Value {
let keys = values.map { $0[keyPath: keyPath] }
self.init(uniqueKeysWithValues: zip(keys, values))
}
}
And merge them like this:
let dict1 = Dictionary(struct1, uniquelyKeyedBy: \.id)
let dict2 = Dictionary(struct2, uniquelyKeyedBy: \.id)
let merged = dict1.merging(dict2, uniquingKeysWith: { old, new in old }).values
This leaves merged as [SomeStruct].
Note that this Dictionary(uniquelyKeyedBy:) has the same preconditions as Dictionary(uniqueKeysWithValues:). If there are duplicate keys, it's a programming error and will raise precondition failure.
You could do something like this:
var setOfIds: Set<Int> = []
var struct3 = struct2.filter { setOfIds.insert($0.id).inserted }
struct3 += struct1.filter { setOfIds.insert($0.id).inserted }
The result would be an array of SomeStruct, with all elements with unique ids.
You could define this as a custom operator :
infix operator *>
func *> (lhs: [SomeStruct], rhs: [SomeStruct]) -> [SomeStruct] {
var setOfIds: Set<Int> = []
var union = lhs.filter { setOfIds.insert($0.id).inserted }
union += rhs.filter { setOfIds.insert($0.id).inserted }
return union
}
Your code would then look like this:
func uniqueById() {
let struct3 = struct2 *> struct1
//use struct3
}
The short answer is no. Swift sets do not have any way to accept a custom comparator and if you absolutely must have a Set, then your wrapper idea is the only way to do it. I question the requirement for a set though.
Instead of using Set in your calculator, I recommend using dictionary.
You can use a Dictionary to produce an array where each item has a unique ID...
let struct3 = Dictionary(grouping: struct1 + struct2, by: { $0.id })
.compactMap { $0.value.max(by: { $0.age < $1.age })}
Or you can keep the elements in a [Int: SomeStruct] dictionary:
let keysAndValues = (struct1 + struct2).map { ($0.id, $0) }
let dictionary = Dictionary(keysAndValues, uniquingKeysWith: { lhs, rhs in
lhs.age > rhs.age ? lhs : rhs
})

Swift order objects by property

I have an array of objects and i would like to order it. Thats normally not a huge problem, but in my special case i would like to order string values like:
CAT-1, CAT-2, ....CAT-10
Where now CAT-10 is before CAT-2.
I already found that i can sort string values in this case with:
let items = items.sorted {
(s1, s2) -> Bool in return s1.localizedStandardCompare(s2) == .orderedAscending
}
But this is only working when the the array contains only string values. In my case i would like to sort it with something like this:
self.filteredItems.sort{
return $0.position < $1.position
}
But i am not sure how can i combine the function above to solve that special sort order?
Please check:
class Category {
let name: String
init(_ name: String) {
self.name = name
}
}
var catA = Category("CAT-2")
var catB = Category("CAT-10")
var catC = Category("CAT-1")
let items: [Category] = [catA, catB, catC]
let filteredItems: [Category] = items.sorted { (s1, s2) -> Bool in
return s1.name.localizedStandardCompare(s2.name) == .orderedAscending
}
print(filteredItems[0].name, filteredItems[1].name, filteredItems[2].name)
// Output : CAT-1 CAT-2 CAT-10
let sortedBy = items.sorted { (c1, c2) -> Bool in
return c1.name < c2.name
}
print(sortedBy[0].name, sortedBy[1].name, sortedBy[2].name)
// Output : CAT-1 CAT-10 CAT-2

Get index of enum with extension of String,

I have an Enum that looks like this:
enum Status: String {
case online = "online"
case offline = "offline"
case na = "na"
}
I need the String value and I know how to get it, but my question is if it´s possible to get the index value too for each case in the enum.
0 for online, 1 for offline and 2 for na.
I will add more statues in the future.
-------- UPDATE -------
Since swift 4.2 you can do following:
enum Status: String, CaseIterable {
case online
case offline
case na
}
extension CaseIterable where Self: Equatable {
var index: Self.AllCases.Index? {
return Self.allCases.index { self == $0 }
}
}
or as I wrote earlier:
enum Status: Int {
case online = 0
case offline
case na
var index: Int {
return rawValue
}
var value: String {
return String(describing: self)
}
}
-------- ORIGIN ANSWER -------
I'm using this extension:
protocol EnumIterable: RawRepresentable {
static var allValues: [Self] { get }
var index: Int? { get }
}
extension EnumIterable {
static var count: Int {
return allValues.count
}
}
extension EnumIterable where Self.RawValue: Equatable {
var next: Self? {
if let index = Self.allValues.index(where: { rawValue == $0.rawValue }) {
return Self.allValues[safe: index + 1]
}
return nil
}
var index: Int? {
return Self.allValues.index { rawValue == $0.rawValue }
}
}
But you would define allValues variable:
enum Status: String, EnumIterable {
case online = "online"
case offline = "offline"
case na = "na"
static var allValues: [Status] {
return [
.online,
.offline,
.na,
]
}
}
Something similar was solved here (count of enumerations):
How do I get the count of a Swift enum?
Next possibility is to define enum like this:
enum Status: Int {
case online = 0
case offline
case na
var index: Int {
return rawValue
}
var value: String {
return String(describing: self)
}
}
print (Status.online.value) // online
print (Status.online.index) // 0
or
enum Status: Int {
case online = 0
case offline
case na
var index: Int {
return rawValue
}
var value: String {
switch self {
case .online:
return "online"
case .offline:
return "offline"
case .na:
return "na"
}
}
}
print (Status.online.value) // online
print (Status.online.index) // 0
Note: for defining string value, you can use CustomStringConvertible protocol.
Eg:
enum Status: Int, CustomStringConvertible {
case online = 0
case offline
case na
var index: Int {
return rawValue
}
var description: String {
switch self {
case .online:
return "online"
case .offline:
return "offline"
case .na:
return "na"
}
}
}
Great answer of #JMI in Swift 5.
enum MyEnum: CaseIterable {
case one
case two
}
extension CaseIterable where Self: Equatable {
var index: Self.AllCases.Index? {
return Self.allCases.firstIndex { self == $0 }
}
}
How to use:
guard let enumCaseIndex = MyEnum.one.index else { return }
print("Enum case index: ", \(enumCaseIndex)) // prints: 0
As enum in Swift does not have index of its values (please read the post in Martin R's comment), you have to create your self some 'index' function or to map all values to an Array to have the index.
You can implement as in this post or another way to do:
enum Status: String {
case online = "online"
case offline = "offline"
case na = "na"
static func index(of aStatus: Status) -> Int {
let elements = [Status.online, Status.offline, Status.na]
return elements.index(of: aStatus)!
}
static func element(at index: Int) -> Status? {
let elements = [Status.online, Status.offline, Status.na]
if index >= 0 && index < elements.count {
return elements[index]
} else {
return nil
}
}
}
let a = Status.na
//return 2
let index = Status.index(of: a)
//return Status.offline
let element2 = Status.element(at: 1)
//return nil
let element3 = Status.element(at: 3)
I did use a solution witch is almost the same than santhosh-shettigar:
func toInt() -> Int {
let allValues: NSArray = MyEnum.allCases as NSArray
let result: Int = allValues.index(of: self)
return result
}
Simple! I use the Swift built-in MyEnum.allCases, ...but I'm not sure that in Swift Specification, we have the guaranty that the Array return by MyEnum.allCases is always in the same order, the one used at the MyEnum definition???
How about this.
enum Status: Int {
case online = 0
case offline = 1
case na = 2
}
You can get the string value and the integer index both.
// enum as string
let enumName = "\(Status.online)" // `online`
// enum as int value
let enumValue = Status.online.rawValue // 0
// enum from int
let enumm = Status.init(rawValue: 1)
Hope it helps. Thanks.
Possible work around may to associate custom functions with enum
enum ToolbarType : String{
case Case = "Case", View="View", Information="Information"
static let allValues = [Case, View, Information]
func ordinal() -> Int{
return ToolbarType.allValues.index(of: self)!
}
}
Can be used as
for item in ToolbarType.allValues {
print("\(item.rawValue): \(item.ordinal())")
}
Output
Case: 0
View: 1
Information: 2

Swift: How to get the size of an enum? [duplicate]

How can I determine the number of cases in a Swift enum?
(I would like to avoid manually enumerating through all the values, or using the old "enum_count trick" if possible.)
As of Swift 4.2 (Xcode 10) you can declare
conformance to the CaseIterable protocol, this works for all
enumerations without associated values:
enum Stuff: CaseIterable {
case first
case second
case third
case forth
}
The number of cases is now simply obtained with
print(Stuff.allCases.count) // 4
For more information, see
SE-0194 Derived Collection of Enum Cases
I have a blog post that goes into more detail on this, but as long as your enum's raw type is an integer, you can add a count this way:
enum Reindeer: Int {
case Dasher, Dancer, Prancer, Vixen, Comet, Cupid, Donner, Blitzen
case Rudolph
static let count: Int = {
var max: Int = 0
while let _ = Reindeer(rawValue: max) { max += 1 }
return max
}()
}
Xcode 10 update
Adopt the CaseIterable protocol in the enum, it provides a static allCases property which contains all enum cases as a Collection . Just use of its count property to know how many cases the enum has.
See Martin's answer for an example (and upvote his answers rather than mine)
Warning: the method below doesn't seem to work anymore.
I'm not aware of any generic method to count the number of enum cases. I've noticed however that the hashValue property of the enum cases is incremental, starting from zero, and with the order determined by the order in which the cases are declared. So, the hash of the last enum plus one corresponds to the number of cases.
For example with this enum:
enum Test {
case ONE
case TWO
case THREE
case FOUR
static var count: Int { return Test.FOUR.hashValue + 1}
}
count returns 4.
I cannot say if that's a rule or if it will ever change in the future, so use at your own risk :)
I define a reusable protocol which automatically performs the case count based on the approach posted by Nate Cook.
protocol CaseCountable {
static var caseCount: Int { get }
}
extension CaseCountable where Self: RawRepresentable, Self.RawValue == Int {
internal static var caseCount: Int {
var count = 0
while let _ = Self(rawValue: count) {
count += 1
}
return count
}
}
Then I can reuse this protocol for example as follows:
enum Planet : Int, CaseCountable {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
//..
print(Planet.caseCount)
Create static allValues array as shown in this answer
enum ProductCategory : String {
case Washers = "washers", Dryers = "dryers", Toasters = "toasters"
static let allValues = [Washers, Dryers, Toasters]
}
...
let count = ProductCategory.allValues.count
This is also helpful when you want to enumerate the values, and works for all Enum types
If the implementation doesn't have anything against using integer enums, you could add an extra member value called Count to represent the number of members in the enum - see example below:
enum TableViewSections : Int {
case Watchlist
case AddButton
case Count
}
Now you can get the number of members in the enum by calling, TableViewSections.Count.rawValue which will return 2 for the example above.
When you're handling the enum in a switch statement, make sure to throw an assertion failure when encountering the Count member where you don't expect it:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let currentSection: TableViewSections = TableViewSections.init(rawValue:section)!
switch(currentSection) {
case .Watchlist:
return watchlist.count
case .AddButton:
return 1
case .Count:
assert(false, "Invalid table view section!")
}
}
This kind of function is able to return the count of your enum.
Swift 2:
func enumCount<T: Hashable>(_: T.Type) -> Int {
var i = 1
while (withUnsafePointer(&i) { UnsafePointer<T>($0).memory }).hashValue != 0 {
i += 1
}
return i
}
Swift 3:
func enumCount<T: Hashable>(_: T.Type) -> Int {
var i = 1
while (withUnsafePointer(to: &i, {
return $0.withMemoryRebound(to: T.self, capacity: 1, { return $0.pointee })
}).hashValue != 0) {
i += 1
}
return i
}
String Enum with Index
enum eEventTabType : String {
case Search = "SEARCH"
case Inbox = "INBOX"
case Accepted = "ACCEPTED"
case Saved = "SAVED"
case Declined = "DECLINED"
case Organized = "ORGANIZED"
static let allValues = [Search, Inbox, Accepted, Saved, Declined, Organized]
var index : Int {
return eEventTabType.allValues.indexOf(self)!
}
}
count : eEventTabType.allValues.count
index : objeEventTabType.index
Enjoy :)
Oh hey everybody, what about unit tests?
func testEnumCountIsEqualToNumberOfItemsInEnum() {
var max: Int = 0
while let _ = Test(rawValue: max) { max += 1 }
XCTAssert(max == Test.count)
}
This combined with Antonio's solution:
enum Test {
case one
case two
case three
case four
static var count: Int { return Test.four.hashValue + 1}
}
in the main code gives you O(1) plus you get a failing test if someone adds an enum case five and doesn't update the implementation of count.
This function relies on 2 undocumented current(Swift 1.1) enum behavior:
Memory layout of enum is just a index of case. If case count is from 2 to 256, it's UInt8.
If the enum was bit-casted from invalid case index, its hashValue is 0
So use at your own risk :)
func enumCaseCount<T:Hashable>(t:T.Type) -> Int {
switch sizeof(t) {
case 0:
return 1
case 1:
for i in 2..<256 {
if unsafeBitCast(UInt8(i), t).hashValue == 0 {
return i
}
}
return 256
case 2:
for i in 257..<65536 {
if unsafeBitCast(UInt16(i), t).hashValue == 0 {
return i
}
}
return 65536
default:
fatalError("too many")
}
}
Usage:
enum Foo:String {
case C000 = "foo"
case C001 = "bar"
case C002 = "baz"
}
enumCaseCount(Foo) // -> 3
I wrote a simple extension which gives all enums where raw value is integer a count property:
extension RawRepresentable where RawValue: IntegerType {
static var count: Int {
var i: RawValue = 0
while let _ = Self(rawValue: i) {
i = i.successor()
}
return Int(i.toIntMax())
}
}
Unfortunately it gives the count property to OptionSetType where it won't work properly, so here is another version which requires explicit conformance to CaseCountable protocol for any enum which cases you want to count:
protocol CaseCountable: RawRepresentable {}
extension CaseCountable where RawValue: IntegerType {
static var count: Int {
var i: RawValue = 0
while let _ = Self(rawValue: i) {
i = i.successor()
}
return Int(i.toIntMax())
}
}
It's very similar to the approach posted by Tom Pelaia, but works with all integer types.
enum EnumNameType: Int {
case first
case second
case third
static var count: Int { return EnumNameType.third.rawValue + 1 }
}
print(EnumNameType.count) //3
OR
enum EnumNameType: Int {
case first
case second
case third
case count
}
print(EnumNameType.count.rawValue) //3
*On Swift 4.2 (Xcode 10) can use:
enum EnumNameType: CaseIterable {
case first
case second
case third
}
print(EnumNameType.allCases.count) //3
Of course, it's not dynamic but for many uses you can get by with a static var added to your Enum
static var count: Int{ return 7 }
and then use it as EnumName.count
For my use case, in a codebase where multiple people could be adding keys to an enum, and these cases should all be available in the allKeys property, it's important that allKeys be validated against the keys in the enum. This is to avoid someone forgetting to add their key to the all keys list. Matching the count of the allKeys array(first created as a set to avoid dupes) against the number of keys in the enum ensures that they are all present.
Some of the answers above show the way to achieve this in Swift 2 but none work in Swift 3. Here is the Swift 3 formatted version:
static func enumCount<T: Hashable>(_ t: T.Type) -> Int {
var i = 1
while (withUnsafePointer(to: &i) {
$0.withMemoryRebound(to:t.self, capacity:1) { $0.pointee.hashValue != 0 }
}) {
i += 1
}
return i
}
static var allKeys: [YourEnumTypeHere] {
var enumSize = enumCount(YourEnumTypeHere.self)
let keys: Set<YourEnumTypeHere> = [.all, .your, .cases, .here]
guard keys.count == enumSize else {
fatalError("Missmatch between allKeys(\(keys.count)) and actual keys(\(enumSize)) in enum.")
}
return Array(keys)
}
Depending on your use case, you might want to just run the test in development to avoid the overhead of using allKeys on each request
Why do you make it all so complex? The SIMPLEST counter of Int enum is to add:
case Count
In the end. And... viola - now you have the count - fast and simple
enum WeekDays : String , CaseIterable
{
case monday = "Mon"
case tuesday = "Tue"
case wednesday = "Wed"
case thursday = "Thu"
case friday = "Fri"
case saturday = "Sat"
case sunday = "Sun"
}
var weekdays = WeekDays.AllCases()
print("\(weekdays.count)")
If you don't want to base your code in the last enum you can create this function inside your enum.
func getNumberOfItems() -> Int {
var i:Int = 0
var exit:Bool = false
while !exit {
if let menuIndex = MenuIndex(rawValue: i) {
i++
}else{
exit = true
}
}
return i
}
A Swift 3 version working with Int type enums:
protocol CaseCountable: RawRepresentable {}
extension CaseCountable where RawValue == Int {
static var count: RawValue {
var i: RawValue = 0
while let _ = Self(rawValue: i) { i += 1 }
return i
}
}
Credits: Based on the answers by bzz and Nate Cook.
Generic IntegerType (in Swift 3 renamed to Integer) is not supported, as it's a heavily fragmented generic type which lacks a lot of functions. successor is not available with Swift 3 anymore.
Be aware that the comment from Code Commander to Nate Cooks answer is still valid:
While nice because you don't need to hardcode a value, this will
instantiate every enum value each time it is called. That is O(n)
instead of O(1).
As far as I know there is currently no workaround when using this as protocol extension (and not implementing in each enum like Nate Cook did) due to static stored properties not being supported in generic types.
Anyway, for small enums this should be no issue. A typical use case would be the section.count for UITableViews as already mentioned by Zorayr.
Extending Matthieu Riegler answer, this is a solution for Swift 3 that doesn't require the use of generics, and can be easily called using the enum type with EnumType.elementsCount:
extension RawRepresentable where Self: Hashable {
// Returns the number of elements in a RawRepresentable data structure
static var elementsCount: Int {
var i = 1
while (withUnsafePointer(to: &i, {
return $0.withMemoryRebound(to: self, capacity: 1, { return
$0.pointee })
}).hashValue != 0) {
i += 1
}
return i
}
I solved this problem for myself by creating a protocol (EnumIntArray) and a global utility function (enumIntArray) that make it very easy to add an "All" variable to any enum (using swift 1.2). The "all" variable will contain an array of all elements in the enum so you can use all.count for the count
It only works with enums that use raw values of type Int but perhaps it can provide some inspiration for other types.
It also addresses the "gap in numbering" and "excessive time to iterate" issues I've read above and elsewhere.
The idea is to add the EnumIntArray protocol to your enum and then define an "all" static variable by calling the enumIntArray function and provide it with the first element (and the last if there are gaps in the numbering).
Because the static variable is only initialized once, the overhead of going through all raw values only hits your program once.
example (without gaps) :
enum Animals:Int, EnumIntArray
{
case Cat=1, Dog, Rabbit, Chicken, Cow
static var all = enumIntArray(Animals.Cat)
}
example (with gaps) :
enum Animals:Int, EnumIntArray
{
case Cat = 1, Dog,
case Rabbit = 10, Chicken, Cow
static var all = enumIntArray(Animals.Cat, Animals.Cow)
}
Here's the code that implements it:
protocol EnumIntArray
{
init?(rawValue:Int)
var rawValue:Int { get }
}
func enumIntArray<T:EnumIntArray>(firstValue:T, _ lastValue:T? = nil) -> [T]
{
var result:[T] = []
var rawValue = firstValue.rawValue
while true
{
if let enumValue = T(rawValue:rawValue++)
{ result.append(enumValue) }
else if lastValue == nil
{ break }
if lastValue != nil
&& rawValue > lastValue!.rawValue
{ break }
}
return result
}
Or you can just define the _count outside the enum, and attach it statically:
let _count: Int = {
var max: Int = 0
while let _ = EnumName(rawValue: max) { max += 1 }
return max
}()
enum EnumName: Int {
case val0 = 0
case val1
static let count = _count
}
That way no matter how many enums you create, it'll only ever be created once.
(delete this answer if static does that)
The following method comes from CoreKit and is similar to the answers some others have suggested. This works with Swift 4.
public protocol EnumCollection: Hashable {
static func cases() -> AnySequence<Self>
static var allValues: [Self] { get }
}
public extension EnumCollection {
public static func cases() -> AnySequence<Self> {
return AnySequence { () -> AnyIterator<Self> in
var raw = 0
return AnyIterator {
let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: self, capacity: 1) { $0.pointee } }
guard current.hashValue == raw else {
return nil
}
raw += 1
return current
}
}
}
public static var allValues: [Self] {
return Array(self.cases())
}
}
enum Weekdays: String, EnumCollection {
case sunday, monday, tuesday, wednesday, thursday, friday, saturday
}
Then you just need to just call Weekdays.allValues.count.
Just want to share a solution when you have an enum with associated values.
enum SomeEnum {
case one
case two(String)
case three(String, Int)
}
CaseIterable doesn't provide allCases automatically.
We can't provide a raw type like Int for your enum to calculate cases count somehow.
What we can do is to use power of switch and fallthrough keyword.
extension SomeEnum {
static var casesCount: Int {
var sum = 0
switch Self.one { // Potential problem
case one:
sum += 1
fallthrough
case two:
sum += 1
fallthrough
case three:
sum += 1
}
return sum
}
}
So now you can say SomeEnum.casesCount.
Remarks:
We still have a problem with switch Self.one {..., we hardcoded the first case. You can easily hack this solution. But I used it just for unit tests so that was not a problem.
If you often need to get cases count in enums with associated values, think about code generation.
struct HashableSequence<T: Hashable>: SequenceType {
func generate() -> AnyGenerator<T> {
var i = 0
return AnyGenerator {
let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
if next.hashValue == i {
i += 1
return next
}
return nil
}
}
}
extension Hashable {
static func enumCases() -> Array<Self> {
return Array(HashableSequence())
}
static var enumCount: Int {
return enumCases().enumCount
}
}
enum E {
case A
case B
case C
}
E.enumCases() // [A, B, C]
E.enumCount // 3
but be careful with usage on non-enum types. Some workaround could be:
struct HashableSequence<T: Hashable>: SequenceType {
func generate() -> AnyGenerator<T> {
var i = 0
return AnyGenerator {
guard sizeof(T) == 1 else {
return nil
}
let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
if next.hashValue == i {
i += 1
return next
}
return nil
}
}
}
extension Hashable {
static func enumCases() -> Array<Self> {
return Array(HashableSequence())
}
static var enumCount: Int {
return enumCases().count
}
}
enum E {
case A
case B
case C
}
Bool.enumCases() // [false, true]
Bool.enumCount // 2
String.enumCases() // []
String.enumCount // 0
Int.enumCases() // []
Int.enumCount // 0
E.enumCases() // [A, B, C]
E.enumCount // 4
It can use a static constant which contains the last value of the enumeration plus one.
enum Color : Int {
case Red, Orange, Yellow, Green, Cyan, Blue, Purple
static let count: Int = Color.Purple.rawValue + 1
func toUIColor() -> UIColor{
switch self {
case .Red:
return UIColor.redColor()
case .Orange:
return UIColor.orangeColor()
case .Yellow:
return UIColor.yellowColor()
case .Green:
return UIColor.greenColor()
case .Cyan:
return UIColor.cyanColor()
case .Blue:
return UIColor.blueColor()
case .Purple:
return UIColor.redColor()
}
}
}
This is minor, but I think a better O(1) solution would be the following (ONLY if your enum is Int starting at x, etc.):
enum Test : Int {
case ONE = 1
case TWO
case THREE
case FOUR // if you later need to add additional enums add above COUNT so COUNT is always the last enum value
case COUNT
static var count: Int { return Test.COUNT.rawValue } // note if your enum starts at 0, some other number, etc. you'll need to add on to the raw value the differential
}
The current selected answer I still believe is the best answer for all enums, unless you are working with Int then I recommend this solution.

How do I get the count of a Swift enum?

How can I determine the number of cases in a Swift enum?
(I would like to avoid manually enumerating through all the values, or using the old "enum_count trick" if possible.)
As of Swift 4.2 (Xcode 10) you can declare
conformance to the CaseIterable protocol, this works for all
enumerations without associated values:
enum Stuff: CaseIterable {
case first
case second
case third
case forth
}
The number of cases is now simply obtained with
print(Stuff.allCases.count) // 4
For more information, see
SE-0194 Derived Collection of Enum Cases
I have a blog post that goes into more detail on this, but as long as your enum's raw type is an integer, you can add a count this way:
enum Reindeer: Int {
case Dasher, Dancer, Prancer, Vixen, Comet, Cupid, Donner, Blitzen
case Rudolph
static let count: Int = {
var max: Int = 0
while let _ = Reindeer(rawValue: max) { max += 1 }
return max
}()
}
Xcode 10 update
Adopt the CaseIterable protocol in the enum, it provides a static allCases property which contains all enum cases as a Collection . Just use of its count property to know how many cases the enum has.
See Martin's answer for an example (and upvote his answers rather than mine)
Warning: the method below doesn't seem to work anymore.
I'm not aware of any generic method to count the number of enum cases. I've noticed however that the hashValue property of the enum cases is incremental, starting from zero, and with the order determined by the order in which the cases are declared. So, the hash of the last enum plus one corresponds to the number of cases.
For example with this enum:
enum Test {
case ONE
case TWO
case THREE
case FOUR
static var count: Int { return Test.FOUR.hashValue + 1}
}
count returns 4.
I cannot say if that's a rule or if it will ever change in the future, so use at your own risk :)
I define a reusable protocol which automatically performs the case count based on the approach posted by Nate Cook.
protocol CaseCountable {
static var caseCount: Int { get }
}
extension CaseCountable where Self: RawRepresentable, Self.RawValue == Int {
internal static var caseCount: Int {
var count = 0
while let _ = Self(rawValue: count) {
count += 1
}
return count
}
}
Then I can reuse this protocol for example as follows:
enum Planet : Int, CaseCountable {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
//..
print(Planet.caseCount)
Create static allValues array as shown in this answer
enum ProductCategory : String {
case Washers = "washers", Dryers = "dryers", Toasters = "toasters"
static let allValues = [Washers, Dryers, Toasters]
}
...
let count = ProductCategory.allValues.count
This is also helpful when you want to enumerate the values, and works for all Enum types
If the implementation doesn't have anything against using integer enums, you could add an extra member value called Count to represent the number of members in the enum - see example below:
enum TableViewSections : Int {
case Watchlist
case AddButton
case Count
}
Now you can get the number of members in the enum by calling, TableViewSections.Count.rawValue which will return 2 for the example above.
When you're handling the enum in a switch statement, make sure to throw an assertion failure when encountering the Count member where you don't expect it:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let currentSection: TableViewSections = TableViewSections.init(rawValue:section)!
switch(currentSection) {
case .Watchlist:
return watchlist.count
case .AddButton:
return 1
case .Count:
assert(false, "Invalid table view section!")
}
}
This kind of function is able to return the count of your enum.
Swift 2:
func enumCount<T: Hashable>(_: T.Type) -> Int {
var i = 1
while (withUnsafePointer(&i) { UnsafePointer<T>($0).memory }).hashValue != 0 {
i += 1
}
return i
}
Swift 3:
func enumCount<T: Hashable>(_: T.Type) -> Int {
var i = 1
while (withUnsafePointer(to: &i, {
return $0.withMemoryRebound(to: T.self, capacity: 1, { return $0.pointee })
}).hashValue != 0) {
i += 1
}
return i
}
String Enum with Index
enum eEventTabType : String {
case Search = "SEARCH"
case Inbox = "INBOX"
case Accepted = "ACCEPTED"
case Saved = "SAVED"
case Declined = "DECLINED"
case Organized = "ORGANIZED"
static let allValues = [Search, Inbox, Accepted, Saved, Declined, Organized]
var index : Int {
return eEventTabType.allValues.indexOf(self)!
}
}
count : eEventTabType.allValues.count
index : objeEventTabType.index
Enjoy :)
Oh hey everybody, what about unit tests?
func testEnumCountIsEqualToNumberOfItemsInEnum() {
var max: Int = 0
while let _ = Test(rawValue: max) { max += 1 }
XCTAssert(max == Test.count)
}
This combined with Antonio's solution:
enum Test {
case one
case two
case three
case four
static var count: Int { return Test.four.hashValue + 1}
}
in the main code gives you O(1) plus you get a failing test if someone adds an enum case five and doesn't update the implementation of count.
This function relies on 2 undocumented current(Swift 1.1) enum behavior:
Memory layout of enum is just a index of case. If case count is from 2 to 256, it's UInt8.
If the enum was bit-casted from invalid case index, its hashValue is 0
So use at your own risk :)
func enumCaseCount<T:Hashable>(t:T.Type) -> Int {
switch sizeof(t) {
case 0:
return 1
case 1:
for i in 2..<256 {
if unsafeBitCast(UInt8(i), t).hashValue == 0 {
return i
}
}
return 256
case 2:
for i in 257..<65536 {
if unsafeBitCast(UInt16(i), t).hashValue == 0 {
return i
}
}
return 65536
default:
fatalError("too many")
}
}
Usage:
enum Foo:String {
case C000 = "foo"
case C001 = "bar"
case C002 = "baz"
}
enumCaseCount(Foo) // -> 3
I wrote a simple extension which gives all enums where raw value is integer a count property:
extension RawRepresentable where RawValue: IntegerType {
static var count: Int {
var i: RawValue = 0
while let _ = Self(rawValue: i) {
i = i.successor()
}
return Int(i.toIntMax())
}
}
Unfortunately it gives the count property to OptionSetType where it won't work properly, so here is another version which requires explicit conformance to CaseCountable protocol for any enum which cases you want to count:
protocol CaseCountable: RawRepresentable {}
extension CaseCountable where RawValue: IntegerType {
static var count: Int {
var i: RawValue = 0
while let _ = Self(rawValue: i) {
i = i.successor()
}
return Int(i.toIntMax())
}
}
It's very similar to the approach posted by Tom Pelaia, but works with all integer types.
enum EnumNameType: Int {
case first
case second
case third
static var count: Int { return EnumNameType.third.rawValue + 1 }
}
print(EnumNameType.count) //3
OR
enum EnumNameType: Int {
case first
case second
case third
case count
}
print(EnumNameType.count.rawValue) //3
*On Swift 4.2 (Xcode 10) can use:
enum EnumNameType: CaseIterable {
case first
case second
case third
}
print(EnumNameType.allCases.count) //3
Of course, it's not dynamic but for many uses you can get by with a static var added to your Enum
static var count: Int{ return 7 }
and then use it as EnumName.count
For my use case, in a codebase where multiple people could be adding keys to an enum, and these cases should all be available in the allKeys property, it's important that allKeys be validated against the keys in the enum. This is to avoid someone forgetting to add their key to the all keys list. Matching the count of the allKeys array(first created as a set to avoid dupes) against the number of keys in the enum ensures that they are all present.
Some of the answers above show the way to achieve this in Swift 2 but none work in Swift 3. Here is the Swift 3 formatted version:
static func enumCount<T: Hashable>(_ t: T.Type) -> Int {
var i = 1
while (withUnsafePointer(to: &i) {
$0.withMemoryRebound(to:t.self, capacity:1) { $0.pointee.hashValue != 0 }
}) {
i += 1
}
return i
}
static var allKeys: [YourEnumTypeHere] {
var enumSize = enumCount(YourEnumTypeHere.self)
let keys: Set<YourEnumTypeHere> = [.all, .your, .cases, .here]
guard keys.count == enumSize else {
fatalError("Missmatch between allKeys(\(keys.count)) and actual keys(\(enumSize)) in enum.")
}
return Array(keys)
}
Depending on your use case, you might want to just run the test in development to avoid the overhead of using allKeys on each request
Why do you make it all so complex? The SIMPLEST counter of Int enum is to add:
case Count
In the end. And... viola - now you have the count - fast and simple
enum WeekDays : String , CaseIterable
{
case monday = "Mon"
case tuesday = "Tue"
case wednesday = "Wed"
case thursday = "Thu"
case friday = "Fri"
case saturday = "Sat"
case sunday = "Sun"
}
var weekdays = WeekDays.AllCases()
print("\(weekdays.count)")
If you don't want to base your code in the last enum you can create this function inside your enum.
func getNumberOfItems() -> Int {
var i:Int = 0
var exit:Bool = false
while !exit {
if let menuIndex = MenuIndex(rawValue: i) {
i++
}else{
exit = true
}
}
return i
}
A Swift 3 version working with Int type enums:
protocol CaseCountable: RawRepresentable {}
extension CaseCountable where RawValue == Int {
static var count: RawValue {
var i: RawValue = 0
while let _ = Self(rawValue: i) { i += 1 }
return i
}
}
Credits: Based on the answers by bzz and Nate Cook.
Generic IntegerType (in Swift 3 renamed to Integer) is not supported, as it's a heavily fragmented generic type which lacks a lot of functions. successor is not available with Swift 3 anymore.
Be aware that the comment from Code Commander to Nate Cooks answer is still valid:
While nice because you don't need to hardcode a value, this will
instantiate every enum value each time it is called. That is O(n)
instead of O(1).
As far as I know there is currently no workaround when using this as protocol extension (and not implementing in each enum like Nate Cook did) due to static stored properties not being supported in generic types.
Anyway, for small enums this should be no issue. A typical use case would be the section.count for UITableViews as already mentioned by Zorayr.
Extending Matthieu Riegler answer, this is a solution for Swift 3 that doesn't require the use of generics, and can be easily called using the enum type with EnumType.elementsCount:
extension RawRepresentable where Self: Hashable {
// Returns the number of elements in a RawRepresentable data structure
static var elementsCount: Int {
var i = 1
while (withUnsafePointer(to: &i, {
return $0.withMemoryRebound(to: self, capacity: 1, { return
$0.pointee })
}).hashValue != 0) {
i += 1
}
return i
}
I solved this problem for myself by creating a protocol (EnumIntArray) and a global utility function (enumIntArray) that make it very easy to add an "All" variable to any enum (using swift 1.2). The "all" variable will contain an array of all elements in the enum so you can use all.count for the count
It only works with enums that use raw values of type Int but perhaps it can provide some inspiration for other types.
It also addresses the "gap in numbering" and "excessive time to iterate" issues I've read above and elsewhere.
The idea is to add the EnumIntArray protocol to your enum and then define an "all" static variable by calling the enumIntArray function and provide it with the first element (and the last if there are gaps in the numbering).
Because the static variable is only initialized once, the overhead of going through all raw values only hits your program once.
example (without gaps) :
enum Animals:Int, EnumIntArray
{
case Cat=1, Dog, Rabbit, Chicken, Cow
static var all = enumIntArray(Animals.Cat)
}
example (with gaps) :
enum Animals:Int, EnumIntArray
{
case Cat = 1, Dog,
case Rabbit = 10, Chicken, Cow
static var all = enumIntArray(Animals.Cat, Animals.Cow)
}
Here's the code that implements it:
protocol EnumIntArray
{
init?(rawValue:Int)
var rawValue:Int { get }
}
func enumIntArray<T:EnumIntArray>(firstValue:T, _ lastValue:T? = nil) -> [T]
{
var result:[T] = []
var rawValue = firstValue.rawValue
while true
{
if let enumValue = T(rawValue:rawValue++)
{ result.append(enumValue) }
else if lastValue == nil
{ break }
if lastValue != nil
&& rawValue > lastValue!.rawValue
{ break }
}
return result
}
Or you can just define the _count outside the enum, and attach it statically:
let _count: Int = {
var max: Int = 0
while let _ = EnumName(rawValue: max) { max += 1 }
return max
}()
enum EnumName: Int {
case val0 = 0
case val1
static let count = _count
}
That way no matter how many enums you create, it'll only ever be created once.
(delete this answer if static does that)
The following method comes from CoreKit and is similar to the answers some others have suggested. This works with Swift 4.
public protocol EnumCollection: Hashable {
static func cases() -> AnySequence<Self>
static var allValues: [Self] { get }
}
public extension EnumCollection {
public static func cases() -> AnySequence<Self> {
return AnySequence { () -> AnyIterator<Self> in
var raw = 0
return AnyIterator {
let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: self, capacity: 1) { $0.pointee } }
guard current.hashValue == raw else {
return nil
}
raw += 1
return current
}
}
}
public static var allValues: [Self] {
return Array(self.cases())
}
}
enum Weekdays: String, EnumCollection {
case sunday, monday, tuesday, wednesday, thursday, friday, saturday
}
Then you just need to just call Weekdays.allValues.count.
Just want to share a solution when you have an enum with associated values.
enum SomeEnum {
case one
case two(String)
case three(String, Int)
}
CaseIterable doesn't provide allCases automatically.
We can't provide a raw type like Int for your enum to calculate cases count somehow.
What we can do is to use power of switch and fallthrough keyword.
extension SomeEnum {
static var casesCount: Int {
var sum = 0
switch Self.one { // Potential problem
case one:
sum += 1
fallthrough
case two:
sum += 1
fallthrough
case three:
sum += 1
}
return sum
}
}
So now you can say SomeEnum.casesCount.
Remarks:
We still have a problem with switch Self.one {..., we hardcoded the first case. You can easily hack this solution. But I used it just for unit tests so that was not a problem.
If you often need to get cases count in enums with associated values, think about code generation.
struct HashableSequence<T: Hashable>: SequenceType {
func generate() -> AnyGenerator<T> {
var i = 0
return AnyGenerator {
let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
if next.hashValue == i {
i += 1
return next
}
return nil
}
}
}
extension Hashable {
static func enumCases() -> Array<Self> {
return Array(HashableSequence())
}
static var enumCount: Int {
return enumCases().enumCount
}
}
enum E {
case A
case B
case C
}
E.enumCases() // [A, B, C]
E.enumCount // 3
but be careful with usage on non-enum types. Some workaround could be:
struct HashableSequence<T: Hashable>: SequenceType {
func generate() -> AnyGenerator<T> {
var i = 0
return AnyGenerator {
guard sizeof(T) == 1 else {
return nil
}
let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory }
if next.hashValue == i {
i += 1
return next
}
return nil
}
}
}
extension Hashable {
static func enumCases() -> Array<Self> {
return Array(HashableSequence())
}
static var enumCount: Int {
return enumCases().count
}
}
enum E {
case A
case B
case C
}
Bool.enumCases() // [false, true]
Bool.enumCount // 2
String.enumCases() // []
String.enumCount // 0
Int.enumCases() // []
Int.enumCount // 0
E.enumCases() // [A, B, C]
E.enumCount // 4
It can use a static constant which contains the last value of the enumeration plus one.
enum Color : Int {
case Red, Orange, Yellow, Green, Cyan, Blue, Purple
static let count: Int = Color.Purple.rawValue + 1
func toUIColor() -> UIColor{
switch self {
case .Red:
return UIColor.redColor()
case .Orange:
return UIColor.orangeColor()
case .Yellow:
return UIColor.yellowColor()
case .Green:
return UIColor.greenColor()
case .Cyan:
return UIColor.cyanColor()
case .Blue:
return UIColor.blueColor()
case .Purple:
return UIColor.redColor()
}
}
}
This is minor, but I think a better O(1) solution would be the following (ONLY if your enum is Int starting at x, etc.):
enum Test : Int {
case ONE = 1
case TWO
case THREE
case FOUR // if you later need to add additional enums add above COUNT so COUNT is always the last enum value
case COUNT
static var count: Int { return Test.COUNT.rawValue } // note if your enum starts at 0, some other number, etc. you'll need to add on to the raw value the differential
}
The current selected answer I still believe is the best answer for all enums, unless you are working with Int then I recommend this solution.