Swift 中的一些关键字

2017-11-07  本文已影响8人  keisme
switch integerToDescribe {  
case 1, 3, 5, 7, 11, 13, 17, 19:  
    description += " a prime number, and also";  
    fallthrough      // 执行到此并不跳出循环,而是继续执行case5
case 5:  
    description += " an integer"    // 执行到这一步,跳出循环
default :  
    description += " finished"  
}
let yetAnotherPoint = (1, -1)  
switch yetAnotherPoint {  
case let (x, y) where x == y:  
println("(\\(x), \\(y)) is on the line x == y")  
case let (x, y) where x == -y:  
println("(\\(x), \\(y)) is on the line x == -y")  
case let (x, y):  
println("(\\(x), \\(y)) is just some arbitrary point")
for view : AnyObject in self.view.subviews  
{  
  if view is UIButton  
  {  
      let btn = view as UIButton;  
      println(btn)  
  }  
}

as 使用场合:

  1. 向上转型:
class Animal {}
class Cat: Animal {}
let cat = Cat()
let animal = cat as Animal
  1. 数值类型转换:
let num1 = 42 as CGFloat
let num2 = 42 as Int
let num3 = 42.5 as Int
let num4 = (42 / 2) as Double
  1. switch 语句
switch animal {
    case let cat as Cat:
    print("如果是Cat类型对象,则做相应处理")
    case let dog as Dog:
    print("如果是Dog类型对象,则做相应处理")
    default: break
}

as! 用于强制转换,转换失败会导致程序崩溃,而 as? 转换失败时会返回一个 nil 对象。

func test(input: Int?) {
    guard let _ = input else {
        print("Input cannot be nil")
        return
    }
}

test(input: nil)
// print "Input cannot be nil"
上一篇 下一篇

猜你喜欢

热点阅读