我正在接受Ray Wenderlich的教程 (http://www.raywenderlich.com/81952/intro-object-oriented-design-swift-part-1)
此功能出错。问题是逻辑OR
运算符(||
)的行。我找不到问题的原因。
功能:
func turn (degrees: Int) -> String {
var normalDegrees = degrees
let degreesInACircle = 360
if (normalDegrees > degreesInACircle || normalDegrees < -degreesInACircle) {
normalDegrees = normalDegrees % degreesInACircle
}
return "Turn \(normalDegrees) degrees"
}
我得到的错误是:Expected "," separator
该函数是类的一部分,但我不明白为什么这应该是一个问题。如果有必要,我会上传代码。我正在使用playground
文件中的代码。
班上其他人:
class Vehicle {
var brandName = ""
var modelName = ""
let modelYear = 0
var powerSource = ""
var numberOfWheels = 0
func goForward() -> String {
return ""
}
func goBackwards() -> String {
return ""
}
func stopMoving() -> String {
return ""
}
func turn (degrees: Int) -> String {
var normalDegrees = degrees
let degreesInACircle = 360
if normalDegrees > degreesInACircle || normalDegrees < -degreesInACircle {
normalDegrees = normalDegrees % degreesInACircle
}
return "Turn \(normalDegrees) degrees"
}
func changeGears (newGearName: String) -> String {
return "Put \(modelName) into \(newGearName) gear"
}
func makeNoise () -> String {
return ""
}
}
答案 0 :(得分:1)
if语句中的条件非常奇怪:当第一个值大于第二个值或第二个值大于第一个值时应执行某些操作,那就像检查值是否无关紧要!所以
if normalDegrees > degreesInACircle || normalDegrees < degreesInACircle
等于
if normalDegrees != degreesInACircle
您也可以转换
func turn (degrees: Int) -> String {
var normalDegrees = degrees
到
func turn (var normalDegrees: Int) -> String {
(完全相同,更简洁)
您的代码中有一些更奇怪的东西。我认为你真正想要的很简单:
func turn(degrees: Int) -> String {
return "Turn \(degrees % 360) degrees"
}
(试试看)