1. Preface
Half a year has passed in a flash. From SF Express’s previous job-hopping to Flash Yin, I don’t have time to write a good article and criticize myself first. Recently, I am busy with open source projects and deeply experienced it in the process of creating various wheels.Swift
middleenum
For convenience, directly upload the code.
2. Enum in Objective-C
typedef NS_ENUM(NSUInteger, UserType) { UserTypeStudent, UserTypeTeacher, UserTypeStaff, UserTypeAdministrator, UserTypeOther };
This is a standardObjective-C
Style enum definition, declaring a type asNSUInteger
Enumeration ofUserType
, What is its use? In most cases, enumerations play the role of explanation, what is explanation?
Here is an example:
{ "successful": true, "userType": 0 // It may be other values }
Return a string in the backgroundjson
,userType
Probably1~9
,The apes who have stepped on the pit understand that if they use the background to return directlyuserType
When processing the business logic of fields, there may be an embarrassing situation that will affect the whole body. This is not only related to code specifications, but also less digging holes for yourself.
The recommended approach is to return theuserType
Map into an enum, and can be called elsewhere in the code afterwards.userType
The corresponding relationship changes, we only need to change the corresponding enumeration map.
3. Enum in Swift
UsedObjective-C
We will find that sometimes we don't want to use basic type enums, such asNSUInteger
Wait, we want totypedef NS_ENUM(NSUInteger, UserType)
ofNSUInteger
Change toNSString
, but the system does not support defining enums of non-base types, and an error will be reportedis an invaild underlying type
, which leads to the use of enums that are not so flexible. Let's take a lookSwift
Enumeration in
enum CIBlurStyle: String{ case extraLight = "extraLight" case light = "light" case dark = "dark"
This isSwift
The most basic enumeration usage in the following section: we can specify the type of the enumeration, throughThe original value of the enum can be obtained. In addition, we can also pass parameters in the enum, such as:
enum CIBlurHUDType { case guide(Bool) case info(String) case error(Error) case other } func handleEnum(hudType: CIBlurHUDType) -> Void { switch hudType { case .guide(let isAutoHide): // case .info(let tip): // Prompt message case .error(let error): // Handle `error` default: break } } // How to usehandleEnum(.info("This is a prompt text~")) let err = (domain: "Some unknown mistakes happened", code: 110, userInfo: nil) handleEnum(.error(err))
4. How to use enum in Swift flexibly
4.1 Leaning code with enum
Enum in Swift is very convenient to use, examples:
public enum CIImageOperation { case cornerRadius(CGFloat) case scale(CGSize) case zip(CGFloat) case other }
We want to create an image request library. After downloading, we may process the above enum on the image. Without using enum, we may declare many methods, such as:
extensin UIImageView { func setImage(with url: URL, cornerRadius: CGFloat) -> Void {} func setImage(with url: URL, scaleTo: CGSize) -> Void {} func setImage(with url: URL, zip: (Bool, CGFLoat)) -> Void {} }
Come on, let's change the writing style, it looks more concise
extension UIImageView { func setImage(with url: URL, imageOperation: CIImageOperation) -> Void { // Process the image after downloading it switch imageOperation { case .cornerRadius(let cornerRadius): // Cut the corners case .scale(let size): // Size Scaling case .zip(let zipValue): // Compression ratio of picture definition default: break } } } // use(with url: "", imageOperation: .cornerRadius(3.0))
4.2 Use enum to do simple package operations on network request results, etc.
enum CIUrlResponse { case Result(Any) case error(NSError) }
Usually after a network request is completed, a series of returns will be returned.response
,useenum
The characteristics of parameters can be passed. We can use enum to wrap network requests to make them more intuitive and easy to understand, such as the following func:
func getData(with url: URL) -> CIUrlResponse {}
Note: It is very convenient to pass parameters when using enum, but it is still not recommended to pass too many parameters or too complicated Closure
To give a negative example:
enum HUDStyle { case loading(Bool, CGFloat, CGFloat, String) case other(((Bool) -> ())) }
. . . I can't understand what these parameters mean without commenting
So. Enum in Swift is suitable for passing a small number of parameters, or simple Closure. Compared with function, enum assumes more of an explanation role.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.