我正在進行簡單的轉換(例如,英制到公制)。我用(String,Closure)元素創建了一個元組數組。這可以讓我爲轉換(例如「英里到公里」)轉換爲一個選擇器控件,並在一行中引用相關的公式,並將值傳遞給轉換。我遇到的問題是當我使用$ 0 。關閉速記我得到一個錯誤「表達式太複雜,無法在合理的時間來解決。」速記中的閉包數組:Xcode Swift:表達式太複雜,無法在合理的時間內解決
這裏的聲明&代碼工作:
低於初始類聲明的ViewController性能聲明:
var formulaTuple = [(convString: String, convFormula: ((Double) -> Double))]()
分配在viewDidLoad()
formulaTuple = [("miles to kilometers", {(a: Double) -> Double in return (a/0.62137) }),
("kilometers to miles", {(a: Double) -> Double in return (a * 0.62137) }),
("feet to meters", {(a: Double) -> Double in return (a/3.2808) }),
("yards to meters", {(a: Double) -> Double in return (a/1.0936) }),
("meters to feet", {(a: Double) -> Double in return (a * 3.2808) }),
("meters to yards", {(a: Double) -> Double in return (a * 1.0936) }),
("inches to centimeters", {(a: Double) -> Double in return (a/0.39370) }),
("centimeters to inches", {(a: Double) -> Double in return (a * 0.39370) }),
("fahrenheit to celsius", {(a: Double) -> Double in return ((a - 32) * (5/9)) }),
("celsius to fahrenheit", {(a: Double) -> Double in return (a * (9/5) + 32) }),
("quarts to liters", {(a: Double) -> Double in return (a/1.05669) }),
("liters to quarts", {(a: Double) -> Double in return (a * 1.05669) }) ]
而且在代碼中工作調用,其中行是選擇器中被點擊的行,inputValue是要傳遞的內容,outputValue是轉換的結果。
outputValue = formulaTuple [行] .convFormula(inputValue的)當我嘗試使用此語法在viewDidLoad中(修剪下來的聲明
出現問題),而不是上面的synatax:
formulaTuple = [("miles to kilometers", {$0/0.62137 }),
("kilometers to miles", {$0 * 0.62137 }),
("feet to meters", {$0/3.2808 }),
("yards to meters", {$0/1.0936 }),
("meters to feet", {$0 * 3.2808 }),
("meters to yards", {$0 * 1.0936 }),
("inches to centimeters", {$0/0.39370}),
("centimeters to inches", {$0 * 0.39370 }),
("fahrenheit to celsius", {($0 - 32) * (5/9) }),
("celsius to fahrenheit", {$0 * (9/5) + 32 }),
("quarts to liters", {$0/1.05669 }),
("liters to quarts", {$0 * 1.05669 }) ]
我認爲這會更順暢,但它似乎打破了Xcode。思考?我的方法基本上是不健全的,會推薦一個不同的方法? 謝謝!
該結構工作得很好。我重讀了Tuples上的Swift文檔,並更加關注了有關臨時類型的一點。真的很感謝你的建議,見解和背景。謝謝! – Gallaugher