Comparing generic struct types

Edit:

Sorry for the premature answer, it actually doesn’t work, because the compiler will choose the function for different types when called from within another function:

func foobar<T,U> (lhs: Foo<T>, rhs: Foo<U>) -> Bool {
    return lhs.sameType(rhs)
}

If you stay in pure Swift territory, the following will work:

Given a simple generic struct

struct Foo<T> {
    let v : T
}

You can define a function sameType that takes to Foos of the same type and just return true:

func sameType<T> (a: Foo<T>, b: Foo<T>) -> Bool {
    return true
}

and overload the function with two different Foos:

func sameType<T,U> (a: Foo<T>, b: Foo<U>) -> Bool {
    return false;
}

The compiler will choose a method based on the argument type:

let a = Foo(v: 1.0)
let b = Foo(v: "asdf")
sameType(a, b) // false
sameType(a, a) // true

This works the same way with instance methods on the struct:

    func sameType (other: Foo) -> Bool {
        return true
    }

    func sameType<U> (other: Foo<U>) -> Bool {
        return false
    }

This can have unexpected results if you mix Swift and Objective-C or have to rely on the dynamic type for other reasons:

import Foundation
let x = NSArray(object: 1)
let y = NSArray(object: "string")
sameType(Foo(v: x[0]), Foo(v: y[0])) // true

The result is true because because Foo(v: x[0]) has type Foo<AnyObject>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)