【问题标题】:Dictionary as function return type字典作为函数返回类型
【发布时间】:2014-08-10 08:32:59
【问题描述】:

我正在关注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
}

这些是错误:

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

【问题讨论】:

  • 您的代码在我的测试项目中编译良好(当我删除未知函数 calcTipWithTipPct 时)。我认为您应该在函数实现之外搜索语法错误

标签: ios swift


【解决方案1】:

看起来您没有使用最新版本的 Swift(测试版 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
}

【讨论】:

  • 谢谢,我会尝试更新 XCode。我其实是昨天直接从开发者门户下载的,我再试一次。
猜你喜欢
  • 2019-02-01
  • 2017-03-17
  • 2020-08-19
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多