Preface
In Swift, enumeration is a very convenient and very powerful type. We also use it frequently in our daily use.
For example, our most common optional:
enum Optional<T> { case Some(T) case None }
I will not introduce the basic usage of enumerations here, but only record two more useful enumeration usages.
Associated Value
Associated values are an excellent way to append extra information to the enum case.
For example, when we need to pass a series of values into the next class, we generally write several settings like the following code:
struct MyStruct { var value: Int init(_ value: Int?) { if let val = value { = val } else { = Int(INT_MAX) } } } class Two { var value1: String? var value2: Int? var value3: MyStruct? func setValue1(value: String?) { } func setValue2(value: Int?) { } func setValue2(value: MyStruct?) { } }
In this way, when more values need to be passed become, the code will undoubtedly become less beautiful. We can simplify it with enums:
enum ValueBind { case bindStringValue(str: String) case bindIntValue(num: Int) case bindModel(model: MyStruct) } class Two { var value1: String? var value2: Int? var value3: MyStruct? func setValueBind(value: ValueBind) { switch value { case .bindStringValue(let str): print(str) case .bindModel(let model): print() case .bindIntValue(let num) print(num) } } }
After using enumeration of associated values, our code immediately became much more concise.
Custom enumeration type
When we usually use enumerations, when we define value for enumerations, we usually only use a few basic types:
enum Direction { case left case top case right case bottom } enum StringEnum: String { case hello = "hello" case world = "world" } enum IntEnum: Int { case one = 1 case two = 2 }
However, if we need to put our custom type into the enum type, we need to add something to the enum.
enum CustomEnum: RawRepresentable { typealias RawValue = MyStruct case null case one case two init?(rawValue: MyStruct) { switch { case 1: self = .one case 2: self = .two default: self = .null } } var rawValue: MyStruct { switch self { case .one: return MyStruct(1) case .two: return MyStruct(2) default: return MyStruct(nil) } } }
We make the enumeration comply with the RawRepresentable protocol and implement some properties and methods of the protocol:
/* Associate the enumeration's RawValue to the type you want **/ associatedtype RawValue /* Use your associated types to generate enum instances **/ init?(rawValue: ) /* Return the type you defined as RawValue **/ var rawValue: { get }
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.