杂项

元组

var  t1 = (1, 2, 3)
print(t1.0, t1.1, t1.2)
var(a, b, c) = (4, 5, 6)
print(a, b ,c)
let t2 = (first: 1, second: 2, third: 3)
print(t2.1, t2.second)
(a, b, c) = (c, b, a)
print(a, b, c)
func returnTuple() -> (Int, Int, Int) {
    return (1, 3, 5)
}
var (d, e, f) = returnTuple()
print(d, e, f)

defer延时执行

func delayCall(){
    var i = 0
    defer{
        print("First defer:",i)
    }
    i = 1
    defer{
        print("Second defer:",i)
    }
    i = 2
    print("First:",i)
    print("Second!!!")
}
delayCall()

Any可以用任意类型,而AnyObject只能用于class类型

class A{

}
var arr01 = [Any]()
arr01.append(1)
arr01.append(2.0)
arr01.append("ab")
var a1:Double = arr01[1] as! Double

var arr02 = [AnyObject]()
let sa = A()
arr02.append(sa)

@autoclosure

func executeAutoclosure(@autoclosure c: () -> Bool){
    if c() {
        print("True")
    }else{
        print("False")
    }
}
executeAutoclosure(1 > 3)

inout类型的参数

  1. 只能传递变量,并且加&
  2. 可以在函数里面修改函数的参数,同时影响外面的变量
var (b1, b2) = (1, 2)
func swap(inout a: Int, inout b: Int){
    (a, b) = (b, a)
}
swap(&b1, b: &b2)
print(b1, b2)

lazy

1.必须要第一次使用时才执行
2.只会执行一次

var ani = Animal()
print(ani.name)

泛型

//泛型函数
func compare(a: T, b: T) -> Bool{
    return a == b
}
print(compare(1, b: 1.0))
print(compare(1, b: "1"))
func printV(a: T) {
    print(a)
}
printV(1)
printV(2.0)
printV("abc")
//泛型类
class Stack{
    var arr = [T]()
    func push(a:T){
        arr.append(a)
    }
    func pop() -> T{
        return arr.removeLast()
    }
}
var arr1 = Stack()
arr1.push(12)
arr1.push(34)
print(arr1.pop())
print(arr1.pop())

你可能感兴趣的:(杂项)