简体   繁体   中英

How do I find the Max from a group of user inputed Ints using Xcode 11 and swift

Here's what I have so far:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var game1: UITextField!
    @IBOutlet weak var game2: UITextField!
    @IBOutlet weak var game3: UITextField!

    @IBOutlet weak var series: UILabel!
    @IBOutlet weak var average: UILabel!
    @IBOutlet weak var high: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

    }

    @IBAction func calculate(_ sender: Any) {

        let game1Results = Int(game1.text!)
        let game2Results = Int(game2.text!)
        let game3Results = Int(game3.text!)
        let gameResultsArray = [game1Results, game2Results, game3Results]

        high.text = "\(gameResultsArray.max())"
    }
}

I've been trying to use the.max function but I'm getting errors stating I need to refer to conform to "Comparable". I'm pretty new to swift, any help will be much appreciated.

It happens because you try to compare values of optional Int (Int?)

First of all, you should know that not each String can be converted to an Int

Eg '42' will be converted correctly, but 'ie42zx' can't be converted to and Int - that's why Int(String) function returns optional Int (Int?)

'Optional' property says like 'i can have a value, but I can also be nil'. That's why you should unwrap optionals in your code

First, I suggest to avoid force unwraping here.

let game1Results = Int(game1.text!)

It can be done like that:

guard
        let text1 = game1.text,
        let text2 = game2.text,
        let text3 = game3.text
else { return }

You should do that because not every text field contains text, so textField.text property returns an optional String?

Then you can convert your String results to an Int and unwrap these results before compare:

guard
        let game1Results = Int(text1),
        let game2Results = Int(text2),
        let game3Results = Int(text3)
else { return }

I would suggest to read more about optionals in swift and unwrapping (see Optionals paragraph)

I believe your issue is that the Int constructor with a string returns an optional integer value. You're trying to take the max of a bunch of optionals, so it cant figure it out.

You can use the compactMap function on your array before calling max() to filter out the nil values.

gameResultsArray.compactMap{ $0 }.max()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM