二进制运算符'>'不能应用于两个'Int?'操作数

时间:2018-10-31 14:34:33

标签: swift

我刚开始使用Swift,正在学习基础知识。我一直在玩Playgrounds,在测试一些代码时遇到错误。

 //creating a Struct for humans
struct Human {
    var firstName: String? = nil
    var surName: String? = nil
    var age: Int? = nil
    var height: Int? = nil
}

var personA = Human()
personA.firstName = "Jake"
personA.surName = "-"
personA.age = 26
personA.height = 185

print (personA)

if (personA.age == 30) {
    print("You're 30 years old")
} else {
    print("You're not 30")
}


var personB = Human()
personB.firstName = "Andy"
personB.surName = "-"
personB.age = 24
personB.height = 180

print (personB)

if (personA.height > personB.height) { //error here
    print("Person A is taller, he is \(personA.height ?? 1)cms tall")
} else {
    print("not true")
}

有人可以简单地解释为什么我收到错误消息吗?

1 个答案:

答案 0 :(得分:1)

可选参数Int?实际上是枚举

您必须打开高度才能进行比较。

例如

if (personA.height ?? 0 > personB.height ?? 0 ) { //error here
    print("Person A is taller, he is \(personA.height ?? 1)cms tall")
} else {
    print("not true")
}

或者更好的

guard let heightA = personA.height, let heightB = personB.height else {
print("Some paremter is nil")
return
}
if (heightA > heightB) { //error here
    print("Person A is taller, he is \(heightA ?? 1)cms tall")
} else {
    print("not true")
}