let bankDict = [
["bank": "b1", "currency": "c1", "buyrate": 0.11, "sellrate": 1.222, "officialrate": 2.15],
["bank": "b1", "currency": "c2", "buyrate": 3.11, "sellrate": 4.222, "officialrate": 5.15],
["bank": "b1", "currency": "c3", "buyrate": 7.11, "sellrate": 8.222, "officialrate": 9.15]]
我正在尝试创建一个应该从我的数组bankDict
返回 buyrate / sellrate / officialrate 的函数。
到目前为止,我只创建了一个测试逻辑的循环:
for dict in bankDict {
let b = dict["bank"]!
let c = dict["currency"]!
if b == "b1" && c == "c2" {
let br = dict["buyrate"]!
let sr = dict["sellrate"]!
let or = dict["officialrate"]!
println("\(br) -> \(sr) -> \(or)")
}
}
正如预期的那样,我会回复:3.11 -> 4.222 -> 5.15
当我尝试创建功能时:
func showRates (bnk: String, crnc: String) -> (br: Double, sr: Double, or: Double) {
for dict in bankDict {
let b = dict["bank"]!
let c = dict["currency"]!
if b == bnk && c == crnc {
let br = dict["buyrate"]
let sr = dict["sellrate"]
let or = dict["officialrate"]
println("\(br) -> \(sr) -> \(or)")
}
return (br, sr, or)
}
}
我收到错误:use of unresolved identifier 'sr'
答案 0 :(得分:1)
你认为如果b不等于bnk或c到crnc会发生什么?在这种情况下,你的功能需要返回什么?如果要返回nil值,则可以执行以下操作
func showRates (bnk: String, crnc: String) -> (br: Double?, sr: Double?, or: Double?) {
for dict in bankDict {
var b = dict["bank"]!
var c = dict["currency"]!
if b == bnk && c == crnc {
var br = dict["buyrate"] as? Double
var sr = dict["sellrate"] as? Double
var or = dict["officialrate"] as? Double
println("\(br) -> \(sr) -> \(or)")
return (br, sr, or)
}
}
return (nil, nil, nil)
}
答案 1 :(得分:1)
这是一个范围问题。在{em> if-statement 的范围内定义了br
,sr
和or
:
if b == bnk && c == crnc {
let br = dict["buyrate"]
let sr = dict["sellrate"]
let or = dict["officialrate"]
println("\(br) -> \(sr) -> \(or)")
}
因此,它们只能在该代码块中使用 如果你将return语句移动到if语句的一部分就可以了(通过一些其他调整):
let bankDict = [
["bank": "b1", "currency": "c1","buyrate": 0.11, "sellrate": 1.222, "officialrate": 2.15],
["bank": "b1", "currency": "c2","buyrate": 3.11, "sellrate": 4.222, "officialrate": 5.15],
["bank": "b1", "currency": "c3","buyrate": 7.11, "sellrate": 8.222, "officialrate": 9.15]]
func showRates(bank: String, currency: String) -> (buyrate: Double, sellrate: Double, officialrate: Double)? {
for dict in bankDict {
if dict["bank"] == bank && dict["currency"] == currency {
if let buyrate = dict["buyrate"] as? Double,
let sellrate = dict["sellrate"] as? Double,
let officialrate = dict["officialrate"] as? Double {
return (buyrate, sellrate, officialrate)
}
}
}
return nil
}
SwiftStub-Code(不是Swift 1.2版本)