Swift4.0新特性(下)

Swift的180个介绍

  • 一、新增一个swapAt方法

  • for example(可以很方便的互换两个元素)

var numbers = [1,2,3,4,5,6]
print(numbers)  // [1,2,3,4,5,6]
numbers.swapAt(2, 5)
print(numbers)  // [1, 2, 6, 4, 5, 3]
swap(&numbers[0], &numbers[1])
print(numbers)  // [2, 1, 6, 4, 5, 3]
Swift4.0新特性(下)_第1张图片
打印效果.png

  • 二、SE-0148使用泛型下标操作符

  • 正常情况下

struct JSON {
      private var data: [String: Any]
      init(data: [String: Any]) {
          self.data = data
      }
      subscript(key: String) -> Any? {
          return data[key]
      }
}
let json = JSON(data: [
        "name": "MG明明",
        "age": 43
    ])
let name: String? = json["name"] as? String  // "MG明明"
let age: Int? = json["age"] as? Int          // 43
  • 修改泛型

struct JSON {
      private var data: [String: Any]
      init(data: [String: Any]) {
          self.data = data
      }
      subscript (key: String) -> T? {
          return data[key] as? T
      }
}
let json = JSON(data: [
        "name": "MG明明",
        "age": 43
    ])
let name: String? = json["name"]   // "MG明明"
let age: Int? = json["age"]        // 43

  • 三、#SE-0156 Subtype existential
protocol P {}
struct S : P {}
class C : P {}
class D { }
let t: AnyObject & P = S() // Compiler error: S is not of class type
let u: AnyObject & P = C() // Compiles successfully
let v: P & AnyObject = C() // Compiles successfully
let w: P & AnyObject = D() // Compiler error: class D does not conform to protocol P
protocol P {}
class C {}
class D : C { }
class E : C { }
class F : D, P { }
let t: C & D & P = F() // Okay: F is a subclass of D and conforms to P
let u: D & P = t       // Okay: D & P is equivalent to C & D & P
let v: C & D & P = u   // Okay: C & D & P is equivalent to D & P
let w: D & E & P       // Compiler error: D is not a subclass of E or vice-versa


  • 轻轻点击,关注我

轻轻点击,关注我

轻轻点击,关注我微博

浏览我的GitHub


  • 扫一扫,关注我

Swift4.0新特性(下)_第2张图片
扫一扫,关注我.jpg

你可能感兴趣的:(Swift4.0新特性(下))