enum Suit: String { case spades = "♠" case hearts = "♥" case diamonds = "♦" case clubs = "♣" }
For example, how can I do something like:
for suit in Suit { // do something with suit print(suit.rawValue) }
Resulting example:
♠ ♥ ♦ ♣
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string. Custom Enumeration Class.
This post is relevant here https://www.swift-studies.com/blog/2014/6/10/enumerating-enums-in-swift
Essentially the proposed solution is
enum ProductCategory : String { case Washers = "washers", Dryers = "dryers", Toasters = "toasters" static let allValues = [Washers, Dryers, Toasters] } for category in ProductCategory.allValues{ //Do something }
Starting with Swift 4.2 (with Xcode 10), just add protocol conformance to CaseIterable
to benefit from allCases
. To add this protocol conformance, you simply need to write somewhere:
extension Suit: CaseIterable {}
If the enum is your own, you may specify the conformance directly in the declaration:
enum Suit: String, CaseIterable { case spades = "♠"; case hearts = "♥"; case diamonds = "♦"; case clubs = "♣" }
Then the following code will print all possible values:
Suit.allCases.forEach { print($0.rawValue) }
If you need to support Swift 3.x or 4.0, you may mimic the Swift 4.2 implementation by adding the following code:
#if !swift(>=4.2) public protocol CaseIterable { associatedtype AllCases: Collection where AllCases.Element == Self static var allCases: AllCases { get } } extension CaseIterable where Self: Hashable { static var allCases: [Self] { return [Self](AnySequence { () -> AnyIterator<Self> in var raw = 0 var first: Self? return AnyIterator { let current = withUnsafeBytes(of: &raw) { $0.load(as: Self.self) } if raw == 0 { first = current } else if current == first { return nil } raw += 1 return current } }) } } #endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With