Introduction to Swift 3.0 and enum

  • 2020-06-03 08:32:42
  • OfStack

1. Introduction

1. It has been half a year since I moved from sf Preferred to Shanyin. I didn't have time to write articles and criticize myself first Swift In the enum Convenience, directly on the code.

2. enum in ES7en-ES8en

typedef NS_ENUM(NSUInteger, UserType) {

This is one paragraph standard Objective-C Style enumeration definition, declaring 1 type as NSUInteger The enumeration of UserType In most cases, enumeration serves as an explanation. What is an explanation?
Here's an example:

    "successful": true,
    "userType": 0 //  It could be something else 

The background returns 1 string json , userType May be 1~9 Any ape who has trod a pit knows that if he USES the backstage directly he will return userType The processing of the business logic of the field may lead to the whole awkward situation, which is not only related to the code specification, but also less self-digging.

The recommended practice is that which will be returned userType It maps to an enumeration, and then it can be called elsewhere in the code, backstage if userType The correspondence changes, and we only need to change the enumeration mapping that corresponds to it

3. enum in Swift

used Objective-C We'll find that sometimes we don't want to use an enumeration of the underlying type, for example NSUInteger Wait, we want to get typedef NS_ENUM(NSUInteger, UserType) the NSUInteger to NSString , but the system does not support enumerations defining non-base types, and an error will be reported is an invaild underlying type That makes enumeration less flexible to use, so let's take a look Swift The enumeration

enum CIBlurStyle: String{
  case extraLight = "extraLight"
  case light   = "light"
  case dark    = "dark"

This is a Swift In the most basic enumeration usage, we can specify the type of enumeration through CIBlurStyle.extraLight.rawValue We can get the original value of the enumeration. In addition, we can also pass parameters in the enumeration, 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 information 
        case .error(let error):
          //  right  `error`  Do the processing 

//  How to use 
handleEnum(.info(" This is a 1 Paragraph prompt text ~"))

let err = NSError.init(domain: " happened 1 Some secret mistake ", code: 110, userInfo: nil)

4. How to use enum in Swift flexibly

4.1 Use enum to simplify code

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 image as enumerated above. Instead of 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 {}

So let's write it in a different way. It's a little bit more concise

extension UIImageView {
  func setImage(with url: URL, imageOperation: CIImageOperation) -> Void {
    //  Download the picture to process the picture 
    switch imageOperation {
        case .cornerRadius(let cornerRadius):
          //  Cut the rounded 
        case .scale(let size):
          //  Size scale 
        case .zip(let zipValue):
          //  Compression ratio of image sharpness 

//  use 
imagView.setImage(with url: "", imageOperation: .cornerRadius(3.0))

4.2 Use enum to do simple package operations on network request results

enum CIUrlResponse {
  case Result(Any)
  case error(NSError)

Series 1 is usually returned after a network request is completed Objective-C0 , the use of enum With the ability to pass parameters, we can use enum to wrap network requests to make them more intuitive and understandable, as shown in func:

func getData(with url: URL) -> CIUrlResponse {}

Note: enum is convenient to use, but it is not recommended to pass too many parameters, or too complex Closure

Take a negative example:

enum HUDStyle {
    case loading(Bool, CGFloat, CGFloat, String)
    case other(((Bool) -> ()))

. What is the meaning of these parameters without comments

enum in ES93en.Swift is suitable for passing a small number of parameters, or simply Closure, which is more interpretive than function

Related articles: