यदि आप Enum को एक Int Int मान देते हैं यह लूपिंग को बहुत आसान बना देगा।
उदाहरण के लिए, आप anyGenerator
एक ऐसे जनरेटर को प्राप्त करने के लिए उपयोग कर सकते हैं जो आपके मानों में गणना कर सके:
enum Suit: Int, CustomStringConvertible {
case Spades, Hearts, Diamonds, Clubs
var description: String {
switch self {
case .Spades: return "Spades"
case .Hearts: return "Hearts"
case .Diamonds: return "Diamonds"
case .Clubs: return "Clubs"
}
}
static func enumerate() -> AnyGenerator<Suit> {
var nextIndex = Spades.rawValue
return anyGenerator { Suit(rawValue: nextIndex++) }
}
}
// You can now use it like this:
for suit in Suit.enumerate() {
suit.description
}
// or like this:
let allSuits: [Suit] = Array(Suit.enumerate())
हालाँकि, यह काफी सामान्य पैटर्न की तरह दिखता है, क्या यह अच्छा नहीं होगा यदि हम किसी भी प्रकार के एनुम प्रकार को केवल एक प्रोटोकॉल के अनुरूप बना सकते हैं? अच्छी तरह से स्विफ्ट 2.0 और प्रोटोकॉल एक्सटेंशन के साथ, अब हम कर सकते हैं!
बस इसे अपनी परियोजना में जोड़ें:
protocol EnumerableEnum {
init?(rawValue: Int)
static func firstValue() -> Int
}
extension EnumerableEnum {
static func enumerate() -> AnyGenerator<Self> {
var nextIndex = firstRawValue()
return anyGenerator { Self(rawValue: nextIndex++) }
}
static func firstRawValue() -> Int { return 0 }
}
अब किसी भी समय आप एक एनम बनाते हैं (इसलिए जब तक इसका इंट रॉ वैल्यू है), आप इसे प्रोटोकॉल के अनुरूप बना सकते हैं:
enum Rank: Int, EnumerableEnum {
case Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King
}
// ...
for rank in Rank.enumerate() { ... }
यदि आपके enum मान 0
(डिफ़ॉल्ट) से प्रारंभ नहीं होते हैं , तो firstRawValue
विधि को ओवरराइड करें :
enum DeckColor: Int, EnumerableEnum {
case Red = 10, Blue, Black
static func firstRawValue() -> Int { return Red.rawValue }
}
// ...
let colors = Array(DeckColor.enumerate())
जगह सहित अंतिम सूट वर्ग, simpleDescription
साथ अधिक मानक CustomStringConvertible प्रोटोकॉल , इस तरह दिखेगा:
enum Suit: Int, CustomStringConvertible, EnumerableEnum {
case Spades, Hearts, Diamonds, Clubs
var description: String {
switch self {
case .Spades: return "Spades"
case .Hearts: return "Hearts"
case .Diamonds: return "Diamonds"
case .Clubs: return "Clubs"
}
}
}
// ...
for suit in Suit.enumerate() {
print(suit.description)
}
स्विफ्ट 3 सिंटैक्स:
protocol EnumerableEnum {
init?(rawValue: Int)
static func firstRawValue() -> Int
}
extension EnumerableEnum {
static func enumerate() -> AnyIterator<Self> {
var nextIndex = firstRawValue()
let iterator: AnyIterator<Self> = AnyIterator {
defer { nextIndex = nextIndex + 1 }
return Self(rawValue: nextIndex)
}
return iterator
}
static func firstRawValue() -> Int {
return 0
}
}