【问题标题】:Binary operator '>' cannot be applied to two 'Int?' operands [duplicate]二元运算符“>”不能应用于两个“Int?”操作数 [重复]
【发布时间】:2018-10-31 14:34:32
【问题描述】:

我刚刚开始使用 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")
}

谁能简单解释一下为什么我会收到错误消息?

【问题讨论】:

  • 另外,只是一个旁注。在 Swift 中,你通常不会在 if 后面加上括号。
  • 为什么所有结构成员都是可选的?实际上,我不认识任何不老不高的人类。将成员声明为非可选可以解决您的问题。
  • 简单来说:nil 应该如何与其他数字进行比较并不明显。在排序列表中,nil 应该排在第一位(暗示nil 小于任何负数Int)。它应该出现在负数之后但在 0 之前吗?在 0 之后但在积极因素之前?毕竟是积极的?在某些情况下,这些变体中的每一个都可能有意义,因此它们不会为您选择并强制使用一个。他们让您决定如何处理nil

标签: swift


【解决方案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")
}

【讨论】:

  • 您的第一个代码 sn-p 仅提供高度的部分顺序。如果我们称高度为ab,那么a < b 对于(a: 0, b: nil)(a: nil, b: 0) 都是错误的。除其他外,这意味着如果您要根据它对数组进行排序,您将首先获得所有负数,然后是0nil 的不确定混合,然后是所有正数。可能不是你所期望的。如需更好的解决方案,请参阅stackoverflow.com/a/44808567/3141234
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
相关资源
最近更新 更多