字典作为函数返回类型

时间:2014-08-10 08:32:59

标签: ios swift

我跟随RW tutorial to learn about 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
}

这些是错误:

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

1 个答案:

答案 0 :(得分: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
}