2017-05-24 66 views
-2

func gradientOfView(withColours: UIColor..., locations: [NSNumber])迅速变PARAM与阵列

func gradientOfView(withColours: [UIColor], locations: [NSNumber])

哪家比较好?

什么时候使用变量参数替换数组作为参数?

回答

0

可变参数函数接受0或多个参数,见下段

func f0(items: Any...) { 
    print(type(of: items)) 
    items.forEach { (i) in 
     print("\t",i) 
    } 
} 

func f1(items: [Any]) { 
    print(type(of: items)) 
    items.forEach { (i) in 
     print("\t",i) 
    } 
} 

f0(items: 1,2) 
f1(items: [1,2]) 

f0(items: [1,2]) 
f1(items: [1,2]) 

f0() 

它打印

Array<Any> 
    1 
    2 
Array<Any> 
    1 
    2 
Array<Any> 
    [1, 2] 
Array<Any> 
    1 
    2 
Array<Any> 

声明

f1() 

将在编译 产生一个错误。如果你不没有很好的理由用可变参数来声明函数参数,避免它。