美文网首页
Swift 2.2 新特性

Swift 2.2 新特性

作者: Jniying | 来源:发表于2020-04-29 09:33 被阅读0次

1.不赞成 ++ 和 -- 这种写法

swift 上认为 ++ -- 这种不好阅读和理解。这两个运算符都将在Swift 3.0中被删除。

2.不赞成 C语言 的for循环遍历

befor

for var i = 1; i <= 10; i += 1 {
    print("\(i) green bottles")
}

now

for i in 1...10 {
    print("\(i) green bottles")
}

for i in 10...1 {
    print("\(i) green bottles")
}

for i in (1...10).reverse() {
    print("\(i) green bottles")
}

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for number in array {
    print("\(number) green bottles")
}

var array = Array(1...10)

for number in array {
    print("\(number) green bottles")
}

3.比较元组

let singer = ("Taylor", "Swift")
let alien = ("Justin", "Bieber")

func ==  (t1: (T, T), t2: (T, T)) -> Bool {
    return t1.0 == t2.0 && t1.1 == t2.1
}

if singer == alien {
    print("Matching tuples!")
} else {
    print("Non-matching tuples!")
}

4.tuple splat 语法弃用

befor

func describePerson(name: String, age: Int) {
    print("\(name) is \(age) years old")
}

let person = ("Taylor Swift", age: 26)
describePerson(person)

5.更多关键字可以用作参数标签

1.stride(through: 9, by: 2)1.stride(to: 9, by: 2) 会产生不一样的结果

for i in 1.stride(through: 9, by: 2) {
    print(i)
}

repeat 关键字使用

func printGreeting(name: String, repeat repeatCount: Int) {
    for _ in 0 ..< repeatCount {
        print(name)
    }
}

printGreeting("Taylor", repeat: 5)

6.变量参数已弃用

befor

func printGreeting(var name: String, repeat repeatCount: Int) {
    name = name.uppercaseString

    for _ in 0 ..< repeatCount {
        print(name)
    }
}

printGreeting("Taylor", repeat: 5)

now

func printGreeting(name: String, repeat repeatCount: Int) {
    let upperName = name.uppercaseString

    for _ in 0 ..< repeatCount {
        print(upperName)
    }
}

printGreeting("Taylor", repeat: 5)

7.重命名的调试标识符:#line,#function, #file

befor
swift2.1 是 __FILE__, __LINE__, __COLUMN__, and __FUNCTION__
now
#file, #line, #column and #function

func printGreeting(name: String, repeat repeatCount: Int) {
    print("This is on line \(#line) of \(#function)")

    let upperName = name.uppercaseString

    for _ in 0 ..< repeatCount {
        print(upperName)
    }
}

printGreeting("Taylor", repeat: 5)

8. 字符串类型func写法已弃用

befor

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Tap!", style: .Plain, target: self, action: "buttonTaped")

now

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Tap!", style: .Plain, target: self, action: #selector(buttonTaped))

9.版本判断

#if swift(>=2.2)
print("Running Swift 2.2 or later")
#else
print("Running Swift 2.1 or earlier")
#endif
PS参考链接

参考Swift版本差异

相关文章

网友评论

      本文标题:Swift 2.2 新特性

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