课程来自慕课网liuyubobobo老师
Swift3的其他变化
1.Never类型
func myFatalError() -> Never { // Never使得函数有返回值,但是正常情况下没有返回值
print("!!!!!")
fatalError()
}
func mod(_ a: Int, _ b: Int) -> Int? {
guard b != 0 else{
// guard 需要函数有返回值
myFatalError()
}
return a%b
}
mod(10, 0)
2.隐式可选型的类型推测
let a: Int! = 5
let b = a // b: Int?
let c:Int = a // c: Int
let d = a + 0 // d: Int
3.(#keyPath)
let superviewColor = #keyPath(UIView.superview.backgroundColor)
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
view.backgroundColor = UIColor.blue
view.addSubview(label)
label.superview?.backgroundColor // UIColor.blue
label.value(forKeyPath: superviewColor) // UIColor.blue
4.新的索引使用
let str = "Hello,Swift 3"
let j = str.startIndex
let k = str.index(j, offsetBy: 5)
str[k] // ,
str[j..<k] // Hello (Swift 4)
5.FloatintPoint
func hypotenuse<T: FloatingPoint>(_ a: T, _ b: T) -> T {
return (a * a + b * b).squareRoot()
}
let aFloat: Float = 3.0
let bFloat: Float = 4.0
hypotenuse(aFloat, bFloat) // 5
let aCGFloat: CGFloat = 3.0
let bCGFloat: CGFloat = 4.0
hypotenuse(aCGFloat, bCGFloat) // 5
let aDouble: Double = 3.0
let bDouble: Double = 4.0
hypotenuse(aDouble, bDouble) // 5
6.@autoclosure
infix operator ???
func ???<T>(optional: T? , defaultValue: @autoclosure ()->T) -> T{
if let value = optional{ return value}
return defaultValue()
}
let AorB = A() ??? B()
let AorX = A() ??? "X"
网友评论