Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

swift4 - 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.

// these are my two TextFields and the "finish"-Button.

@IBOutlet weak var goalPlayerOne: UITextField!
@IBOutlet weak var goalPlayerTwo: UITextField!
@IBOutlet weak var finishedGameButton: UIButton!

// 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);

// 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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:

1: If let

if let goalOne = Int(someString) {
    // do something with goalOne
}

2: Guard let

guard let goalOne = Int(someString) else {
    // either return or throw an error
}

// do something with goalOne

3: map and/or flatMap

let someValue = Int(someString).map { goalOne in
    // do something with goalOne and return a value
}

4: Provide a default value

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...