Swift 5.0 New Features

Swift 5.0 New Features

Description link

Result<T, Error>

Celebrate, swift 5.0 Result Type will join the official repository. This means that we write in the future such as network callback, organize data, they can like this:

func fetch<T>(result: Result<T, Error>) {
  switch result {
  case .success(let data):
    print("data: \(data)")
  case .failure(let error):
    print("error: \(error)")
  }
}

let result = Result<String, Error>.success("123")
fetch(result: result) // data: 123

// 如果是success的话,可以通过下面的方式取值:
if let s = try? result.get() {
  print(s) // 123
}

// 通过闭包,构造result:
let result = Result { "123" }
复制代码

The original string

Probably both before and after the # symbol, it can be determined to want to express the original meaning, such as:

let rain = #"The "rain" in "Spain" falls mainly on the Spaniards."#
print(rain)
复制代码

Before the case that the double quotes will be represented as a string end, but added a # after, it was believed, double quotes indicate the original meaning, rather than mark the end of the string.

In this regular expression, it would be more useful, it can be less some symbols, such as:

let regex1 = "\\\\[A-Z]+[A-Za-z]+\\.[a-z]+"
复制代码

It can be written as:

let regex2 = #"\\[A-Z]+[A-Za-z]+\.[a-z]+"#
复制代码

Enum treatment in case

When we enumeration enum, which is often not complete enumeration of all the case, and therefore will join the default, but this will be a problem, that if we add a new back case, then forgot to deal with this case plus way, then, the compiler will not complain, do not give us checks, therefore, swift added a new feature called: @unknown, it can remind you in case you add a new time, do not forget to add it handling logic:

enum PPError: Error {
  case short
  case obvious
  case simple
}

func showOld(error: PPError) {
  switch error {
  case .obvious:
    print("obvious...")
  @unknown default:
    print("default...")
  }
}

showOld(error: .simple)
复制代码

The use try? Nested tie optional value

struct User {
  var id: Int
  
  init?(id: Int) {
    if id < 1 {
      return nil
    }
    
    self.id = id
  }
  
  func getMessages() throws -> String {
    // complicated code here
    return "No messages"
  }
}

let user = User(id: 1)
let messages = try? user?.getMessages()
print("\(messages)")
复制代码

Before swift5 output should be: String ?? now just: String?

Determining whether a number is divisible

Swift5.0 a new method, it can be used to determine:

let rowNumber = 4

if rowNumber.isMultiple(of: 2) {
    print("Even")
} else {
    print("Odd")
}

// 之前我们要这么写:

if rowNumber % 2 == 0 {
	
} else {
	
}
复制代码

Using the above method, you can more clearly express the meaning of conditions, polite compiler can help you check.

Expand the value of the dictionary function with compactMapValues

let times = [
  "Hudson": "38",
  "Clarke": "42",
  "Robinson": "35",
  "Hartis": "DNF"
]

let d = times.compactMapValues { Int($0) }
print(d)
复制代码

This method can be nil value as a key removal, and returns a new dictionary.

With a count (where :) function calculates a sequence number that satisfies the conditions

let scores = [100, 80, 85]
let passCount = scores.count { $0 >= 85 } // 2
复制代码

Guess you like

Origin blog.csdn.net/weixin_33733810/article/details/91379907