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循环的情况下拾取此数组的元素。我想,例如用字符串搜索一个元素。 例如,我有一个字符串是" FarToCelsius"我想执行" FarToCelsius"关闭元素。
答案 0 :(得分:2)
这是一个你可以做到的词典:
if let fn = tabClosures["FarToCelsius"] {
let res = fn(2.2, 3.0)
print("\(res)")
}