字典作为函数返回类型

Car*_*izz 10 ios swift

我正在关注一个RW教程以了解Swift,并且我在以下函数声明的第一行遇到错误:

func returnPossibleTips() -> [Int: Double] {
    let possibleTipsInferred = [0.15, 0.18, 0.20]
    let possibleTipsExplicit:[Double] = [0.15, 0.18, 0.20]

    var retval = [Int: Double]()
    for possibleTip in possibleTipsInferred {
        let intPct = Int(possibleTip*100)
        retval[intPct] = calcTipWithTipPct(possibleTip)
    }
    return retval
}
Run Code Online (Sandbox Code Playgroud)

这些是错误:

  • 函数结果的预期类型
  • 一行上的连续声明必须用';'分隔
  • 预期的声明
  • 函数声明中预期的'{'

Ale*_*tyy 9

看起来你没有使用Swift的最新版本(beta 5),在第一版中没有数组的[Int]语法.

你可以更新Xcode或重写这段代码:

func returnPossibleTips() -> Dictionary<Int, Double> {
    let possibleTipsInferred = [0.15, 0.18, 0.20]
    let possibleTipsExplicit:Array<Double> = [0.15, 0.18, 0.20]

    var retval = Dictionary<Int, Double>()
    for possibleTip in possibleTipsInferred {
        let intPct = Int(possibleTip * 100)
        retval[intPct] = calcTipWithTipPct(possibleTip)
    }

    return retval
}
Run Code Online (Sandbox Code Playgroud)