二进制运算符'<'不能应用于两个'Int?'操作数 [英] Binary operator '<' cannot be applied to two 'Int?' operands
问题描述
晚上好可爱的社区,
这是我的第一篇文章,如果我做错了,请留意.
我知道这里也有类似的问题,但我不明白.
也许我理解,如果有人在我的代码中解释它.
Good evening lovely community,
this is my first post, please have mercy, if I do something wrong.
I know there are some similar questions here, but I doesn't understand it.
Maybe I understand, if someone explain it on my code.
//这是我的两个TextField和完成"按钮.
// these are my two TextFields and the "finish"-Button.
@IBOutlet weak var goalPlayerOne: UITextField!
@IBOutlet weak var goalPlayerTwo: UITextField!
@IBOutlet weak var finishedGameButton: UIButton!
//这是我的功能,它应该告诉我,哪个玩家赢得了A< B,所以B赢了.
// here are my function, it should tell me, which Player has won like A < B, so B has won.
@IBAction func finishedGameButtonPressed(_ sender: Any) {
// define UITextField as Integer
let goalPlayerOne = "";
let goalOne = Int(goalPlayerOne);
let goalPlayerTwo = "";
let goalTwo = Int(goalPlayerTwo);
//这是问题所在:
二进制运算符'<'不能应用于两个'Int?'操作数"
//如果我制作了'==',那么就可以了
// here is the problem:
"Binary operator '<' cannot be applied to two 'Int?' operands"
// if I make a '==' it works
if goalOne < goalTwo{
displayMyAlertMessage(userMessage: "Player Two wins")
return
}
推荐答案
如果查看采用String
的Int
初始化程序的声明,您可以在init
之后通过?
看到它返回一个可选的:
If you look at the declaration for Int
's initializer that takes a String
, you can see by the ?
after init
that it returns an optional:
convenience init?(_ description: String)
这意味着您必须先拆开包装,然后才能执行大多数操作(==
是一个例外,因为Optional
类型对该操作符有重载).
This means you have to unwrap it before you can do most things with it (==
is an exception, since the Optional
type has an overload for that operator).
有四种主要方法可以解开可选项:
There are four main ways to unwrap your optionals:
if let goalOne = Int(someString) {
// do something with goalOne
}
2:后卫放手
guard let goalOne = Int(someString) else {
// either return or throw an error
}
// do something with goalOne
3:map
和/或flatMap
3: map
and/or flatMap
let someValue = Int(someString).map { goalOne in
// do something with goalOne and return a value
}
4:提供默认值
let goalOne = Int(someString) ?? 0 // Or whatever the default value should be
如果解开所有可选选项,则可以按预期进行比较.
If you unwrap all your optionals, you'll be able to compare them as you expect.
这篇关于二进制运算符'<'不能应用于两个'Int?'操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!