Binary operator '<' cannot be applied to two 'Int?' operands

后端 未结 3 1028
一向
一向 2020-12-06 07:34

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 under

相关标签:
3条回答
  • 2020-12-06 07:58

    This error can also occur if you are comparing a custom type (ie: struct or class) for which you haven't implemented the Comparable protocol.

    0 讨论(0)
  • 2020-12-06 08:01

    Well, by using guard statement you can check if both values are not nil, and converting it to Int typ

        guard let value_one = Int(goalPlayerOne), let value_two = Int(goalPlayerTwo) else {
            print("Some value is nil")
            return
        }
    

    so you can safely compare two values.

        if value_one < value_two {
           //Do something
        }
    
    0 讨论(0)
  • 2020-12-06 08:10

    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.

    0 讨论(0)
提交回复
热议问题