Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error comparing Int array slice elements in Swift 4 Xcode 9

In my playground in Xcode 9

func somefn<Int>(_ a:[Int])->[Int]{
    if(a.count == 1 || a.isEmpty){
        return a
    }else{
        let e1 = (a.count/2) - 1
        let s2 = e1 + 1

        let lhs = Array(a[...e1])
        let rhs = Array(a[s2...])

        if lhs.first! > rhs.first! {
            print("LHS first is bigger than RHS second")
        }

        return []
    }
}

let s = [1,4,6,9]
somefn(s)

Gives error:

Binary operator '>' cannot be applied to two 'Int' operands

like image 994
idej1234 Avatar asked Dec 07 '25 17:12

idej1234


1 Answers

The issue seems to be that the <Int> syntax after the function name is being treated as a generic type placeholder and not the actual data type of Int.

If you replace <Int> with T in the whole function declaration you still get the error.

func somefn<T>(_ a:[T]) -> [T] {

This makes sense since the < operator is now ambiguous. By updating the signature to indicate that T must be a Comparable, the problem goes away:

func somefn<T:Comparable>(_ a:[T]) -> [T] {

You could also do:

func somefn<Int:Comparable>(_ a:[Int]) -> [Int] {

but that's confusing to any reader since that Int is not the data type of Int.

This all assumes you intend to be able to pass arrays of different data types and get back an array of the same type.

If you just want to support an array of Int for both the parameter and return type, change the signature to:

func somefn(_ a:[Int]) -> [Int] {
like image 191
rmaddy Avatar answered Dec 10 '25 06:12

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!