运算符在swift之后的意外表达式

时间:2016-06-13 19:02:02

标签: xcode swift swift-playground

我对Swift和Playground来说比较新。在游乐场进行实验时,我写了一段Swift代码来计算5个数字的平均值

PropertyDescriptor

然而,它一直给我这个错误“操作符后的意外表达”(参见上面代码中的注释)。有人可以解释原因。

3 个答案:

答案 0 :(得分:1)

错误消息有点误导。

实际的错误原因是count++之间的空格字符 后缀运算符必须直接跟随操作数而没有任何空格。

无论如何,你应该总是使用前向兼容语法

count += 1

答案 1 :(得分:0)

for score in scores {
    total += score
    count ++
}   // Error: unexpected expression after operator

将在Swift 3中删除++快捷方式。您需要执行此操作

for score in scores {
    total += score
    count = count + 1
}   

否则你不能在count和++之间留一个空格

所以

count++

答案 2 :(得分:0)

你可以这样试试:

func average(scores: [Int]) -> Int {
    var avg = 0
    for number in numbers {
        avg += score
    }
    var  ave  = (avg)/(scores.count)
    return ave
}

您只需将total与您声明为0的count分开即可。您需要数组[Int]的计数。所以你需要做scores.count,它给出了该数组中元素的数量。