swiftswiftSwift

Swift 5.0 新特性

2018-11-05  本文已影响82人  HuangJn

参考

what's new in Swfit 5.0
Demo

Raw strings

SE-0200增加了 # 符号,使得写字符串更加简单。

  //before
 let answer = 42
 let dontpanic = "The answer to life, the universe, and everything is \(answer)"
 // after
 let answer = 42
 let dontpanic = #"The answer to life, the universe, and everything is \#(answer)"#

Handling future enum cases

SE-0192 在枚举新增加一个 @unknown 修饰 default 分支,这样使得将来 enum 再增加一个 case 的时候,编译器会在该枚举的switch 代码里生成一个警告
比如

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

    func showOld(error: PasswordError){
             switch error {
             case .short:
                      print("Your password was too short.")
             case .obvious:
                      print("Your password was too obvious.")
             default:
                      print("Your password was too simple.")
             }
    }

上面代码假如我们再加个 case old,执行代码时它会自动进入到default分支,可这并不是我们想要的结果,因为这个密码是一个旧密码而不是密码太简单,这时候可以用 @unknown,如下

  enum PasswordError: Error {
            case short
            case obvious
            case simple
            case old
   }

   func showNew(error: PasswordError) {
        switch error {
        case .short:
            print("Your password was too short.")
        case .obvious:
            print("Your password was too obvious.")
        @unknown default:
            print("Your password wasn't suitable.")
        }
    }

这时会产生一个警告 ,因为新增了case old ,switch没有明确地处理每一个分支。

Checking for integer muliples

SE-0225 integers 新增加了一个 isMultiple(of:) 方法
来检测一个数是否是另一个数的倍数

  let rowNumber = 4

  /*相当于 if rowNumber %  2 == 0
     改成方法调用更易懂,更方便调用(有代码补全)
 */
  if rowNumber.isMultiple(of:2) {
      print("Even")
  } else {
      print("Odd")
  }

Counting matching items in a sequence

SE-0220
Sequence 新增加了一个方法 count(where:) 相当于 filter() + count 的结果,但是它更加简洁一步到位

//before
let scores = [100,80,85]
let passCount = scores.filter{($0 >= 85)}.count

//after 避免生成一个数组
let scores = [100,80,85]
let passCount = scores.count { $0 >= 85}

这个方法适用于遵循了 Sequence 的所有类型,所以也可以用在 集合 和 字典里。

Transforming and unwrapping dictionary values with compactMapValues()

SE-0218 为字典新增了一个方法 compactMapValues(),正如数组的compactMap函数一样,可以过滤nil,类型转换

    let times = [
        "Hudson": "38",
        "Clarke": "42",
        "Robinson": "35",
        "Hartis": "DNF"
    ]
    //通过compactMapValues 将值转换成integer类型,并且将DNF过滤掉
     let finishers1 = times.compactMapValues { Int($0) }
    //也可以这样写
     let finishers2 = times.compactMapValues(Int.init)
  
     // 过滤nil
     let people = [
        "Paul": 38,
        "Sophie": 8,
        "Charlotte": 5,
        "William": nil
      ]
     let knownAges = people.compactMapValues { $0 }

结尾

Swift的每次更新都使得写起代码越来越简单高效。
附上一个网站 What's new in Swift

上一篇 下一篇

猜你喜欢

热点阅读