美文网首页
Swift 3 的新特性

Swift 3 的新特性

作者: coderzcj | 来源:发表于2016-08-02 14:42 被阅读57次
  1. ++ 和 --
    以前:
var i = 0
i++
++i
i--
--i

现在:

var i = 0
i += 1 // 或 i = i + 1
i -= 1 // 或 i = i - 1
  1. C语言风格的for循环
    以前:
for (i = 1; i <= 10; i++) {
  print(i)
}

现在:

for i in 1...10 {
  print(i)
}
或者
(1...10).forEach {
  print($0)
}
  1. 移除函数参数的var,避免和inout混淆
    以前:
func gcd(var a: Int, var b: Int) -> Int {
 
  if (a == b) {
    return a
  }
 
  repeat {
    if (a > b) {
      a = a - b
    } else {
      b = b - a
    }
  } while (a != b)
 
  return a
}

现在:

func gcd(a: Int, b: Int) -> Int {
 
  if (a == b) {
    return a
  }
 
  var c = a
  var d = b
 
  repeat {
    if (c > d) {
      c = c - d
    } else {
      d = d - c
    }
  } while (c != d)
 
  return c
}
  1. 默认添加调用函数时的第一个参数标签
    以前:
gcd(8, b: 12)

现在:

gcd(a: 8, b: 12)

现在迁移到以前:第一个参数标签为_

func gcd(_ a: Int, b: Int) -> Int {

  }
  1. 移除用String生成Selector,用#selector替代
    以前:
button.addTarget(responder, action: "tap", forControlEvents: .TouchUpInside)

现在:

button.addTarget(responder, action: #selector(Responder.tap), for: .touchUpInside)
  1. 移除用String生成keyPath
    以前:
let me = Person(name: "Cosmin")
me.valueForKeyPath("name")

现在:

let me = Person(name: "Cosmin")
me.value(forKeyPath: #keyPath(Person.name))
  1. Foundation 类型去除NS前缀
    以前:
let file = NSBundle.mainBundle().pathForResource("tutorials", ofType: "json")
let url = NSURL(fileURLWithPath: file!)
let data = NSData(contentsOfURL: url)
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: [])
print(son)

现在:

let file = Bundle.main().pathForResource("tutorials", ofType: "json")
let url = URL(fileURLWithPath: file!)
let data = try! Data(contentsOf: url)
let json = try! JSONSerialization.jsonObject(with: data)
print(son)
  1. M_PI vs .pi
    以前:
let r =  3.0
let circumference = 2 * M_PI * r
let area = M_PI * r * r

现在:
Float.pi
Double.pi
CGFloat.pi

let r = 3.0
let circumference = 2 * Double.pi * r
let area = Double.pi * r * r

或使用类型推断

let r = 3.0
let circumference = 2 * .pi * r
let area = .pi * r * r
  1. GCD
    以前:
let queue = dispatch_queue_create("Swift 2.2", nil)
dispatch_async(queue) {
  print("Swift 2.2 queue")
}

现在:

let queue = DispatchQueue(label: "Swift 3")
queue.async {
  print("Swift 3 queue")
}
  1. Core Graphics
    以前:
override func drawRect(rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()
    let blue = UIColor.blueColor().CGColor
    CGContextSetFillColorWithColor(context, blue)
    let red = UIColor.redColor().CGColor
    CGContextSetStrokeColorWithColor(context, red)
    CGContextSetLineWidth(context, 10)
    CGContextAddRect(context, frame)
    CGContextDrawPath(context, .FillStroke)
  }

现在:

 override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else {
      return
    }
    
    let blue = UIColor.blue().cgColor
    context.setFillColor(blue)
    let red = UIColor.red().cgColor
    context.setStrokeColor(red)
    context.setLineWidth(10)
    context.addRect(frame)
    context.drawPath(using: .fillStroke)
  }
  1. 动词 和 名词
  • 方法返回值 - 名词
for i in (1...10).reversed() {
  print(i)
}
var array = [1, 5, 3, 2, 4]
for (index, value) in array.enumerated() {
  print("\(index + 1) \(value)")
}
var array = [1, 5, 3, 2, 4]
let sortedArray = array.sorted()
print(sortedArray)
  • 方法改变值 - 动词
var array = [1, 5, 3, 2, 4]
array.sort()
print(array)
  1. Swift API
    省略不必要的文字,通过上下文推断。
  • XCPlaygroundPage.currentPage becomes PlaygroundPage.current
  • button.setTitle(forState) becomes button.setTitle(for)
  • button.addTarget(action, forControlEvents) becomes button.addTarget(action, for)
  • NSBundle.mainBundle() becomes Bundle.main()
  • NSData(contentsOfURL) becomes URL(contentsOf)
  • NSJSONSerialization.JSONObjectWithData() becomes JSONSerialization.jsonObject(with)
  • UIColor.blueColor() becomes UIColor.blue()
  • UIColor.redColor() becomes UIColor.red()
  1. 枚举
    小写的驼峰标识替代大小的驼峰标识
  • .System becomes .system
  • .TouchUpInside becomes .touchUpInside
  • .FillStroke becomes .fillStroke
  • .CGColor becomes .cgColor
  1. 访问级别
    公开(public)
    内部(internal)
    文件外私有(fileprivate)
    私有(private):即使是在同一个文件当中,私有成员也只能够在对应的作用域当中访问。

  2. 将 inout, @noescape 和 @autoclosure 声明调整为类型修饰

func double(input: inout Int) {
    input = input * 2
}
func noEscape(f: @noescape () -> ()) {}
func noEscape(f: @autoclosure () -> ()) {}
  1. 移除柯里化函数声明语法
    以前:
func curried(x: Int)(y: Int) -> Int {
    return {(y: Int) -> Int in
        return x * y
    }
}

现在:

func curried(x: Int) -> (y: Int) -> Int {
    return {(y: Int) -> Int in
        return x * y
    }
}
  1. 允许(绝大多数)关键词作为参数标签
// Swift 3 calling with argument label:
calculateRevenue(for sales: numberOfCopies,
                 in .dollars)
// Swift 3 declaring with argument label:
calculateRevenue(for sales: Int,
                 in currency: Currency)

参考资料:

What’s New in Swift 3
Swift 3 新特性一览

相关文章

网友评论

      本文标题:Swift 3 的新特性

      本文链接:https://www.haomeiwen.com/subject/rytnjttx.html