मैंने इसे अनुकरण करने का एक तरीका बनाया (मार्कोस क्रिस्पिनो ने उसके उत्तर पर क्या सुझाव दिया उससे अलग नहीं)। एक आदर्श समाधान से बहुत दूर है, लेकिन हम उन अलग-अलग संपत्तियों के लिए उन गंदे स्विच मामलों से बचने की अनुमति देते हैं जिन्हें हम प्राप्त करना चाहते हैं।
चाल "गुण/डेटा" धारक के रूप में संरचना का उपयोग करना और इसे enum में RawValue के रूप में उपयोग करना है।
इसमें कुछ डुप्लिकेशंस है लेकिन यह अब तक मेरी सेवा कर रहा है। हर बार जब आप एक नया एनम केस जोड़ना चाहते हैं, तो संकलक आपको कच्चे वैल्यू गेटटर में अतिरिक्त केस भरने के लिए याद दिलाएगा, जो आपको init?
को अपडेट करने के लिए याद दिलाएगा जो आपको संरचना पर नई स्थैतिक संपत्ति बनाने के लिए याद दिलाएगा।
Gist
सार करने के लिए कोड:
enum VehicleType : RawRepresentable {
struct Vehicle : Equatable {
let name: String
let wheels: Int
static func ==(l: Vehicle, r: Vehicle) -> Bool {
return l.name == r.name && l.wheels == r.wheels
}
static var bike: Vehicle {
return Vehicle(name: "Bicycle", wheels: 2)
}
static var car: Vehicle {
return Vehicle(name: "Automobile", wheels: 4)
}
static var bus: Vehicle {
return Vehicle(name: "Autobus", wheels: 8)
}
}
typealias RawValue = Vehicle
case car
case bus
case bike
var rawValue: RawValue {
switch self {
case .car:
return Vehicle.car
case .bike:
return Vehicle.bike
case .bus:
return Vehicle.bus
}
}
init?(rawValue: RawValue) {
switch rawValue {
case Vehicle.bike:
self = .bike
case Vehicle.car:
self = .car
case Vehicle.bus:
self = .bus
default: return nil
}
}
}
VehicleType.bike.rawValue.name
VehicleType.bike.rawValue.wheels
VehicleType.car.rawValue.wheels
VehicleType(rawValue: .bike)?.rawValue.name => "Bicycle"
VehicleType(rawValue: .bike)?.rawValue.wheels => 2
VehicleType(rawValue: .car)?.rawValue.name => "Automobile"
VehicleType(rawValue: .car)?.rawValue.wheels => 4
VehicleType(rawValue: .bus)?.rawValue.name => "Autobus"
VehicleType(rawValue: .bus)?.rawValue.wheels => 8
स्रोत
2016-11-28 14:35:13
विवरण के साथ एक संबद्ध मूल्य जो मैं चाहता के लिए सही नहीं होगा। सभी 'टीपोट' उदाहरणों में एक ही स्ट्रिंग होनी चाहिए; अगर मैं एक विशेष त्रुटि उदाहरण के स्रोत पर एक नोट संलग्न करना चाहता हूं, तो मैं एक संबंधित स्ट्रिंग मान का उपयोग करूंगा। –