2015-11-13 70 views
1
let tabClosures = [ 
"Adicionar": {(a:Float, b:Float)-> Float in var varaux = a + b; return varaux;},  "Subtrair":{(a:Float, b:Float)-> Float in var varaux = a - b; return varaux;},  "Multiplicar": {$0 * $1},  
"FarToCelsius": { (a:Float, b:Float) -> Float in var varaux = (a * 9/5 + 32); return varaux;},  
"CelsiusToFar": { (a:Float, b:Float) -> Float in var varaux = (a - 32)*5/9; return varaux;},  
"KelvinToCelsius": { (a:Float, b:Float) -> Float in var varaux = (a - 273.15); return varaux;},  
"CelsiusToKelvin": { (a:Float, b:Float) -> Float in var varaux = (a + 273.15); return varaux;} ] 
let val1:Float = 120.1 
let val2:Float = 10.1 
for(x, y) in tabClosures{  
if(x == "FarToCelsius"){   
print("\(x): \(y(val1, val2))")}  
else  if(x == "CelsiusToFar"){   
print("\(x): \(y(val1, val2))")}} 

如何在沒有For循環的情況下拾取這個數組的元素。我想,例如用一個字符串搜索一個元素。 Foor示例我有一個字符串是「FarToCelsius」,我想執行「FarToCelsius」關閉元素。Swift Array of Closures - 查找元素

回答

2

這是一個字典,你可以做到這一點:

if let fn = tabClosures["FarToCelsius"] { 
    let res = fn(2.2, 3.0) 
    print("\(res)") 
} 
+0

謝謝你,我不知道這是一本字典。我正在開始研究斯威夫特 – cacc