ios – In Swift, tips on how to use generic sort for an argument of a operate?


I outlined a generic class in Swift.

    class MyClass<T> {
        
    }

I can instantiate MyClass<Int> and assign it to a variable whose sort is MyClass with out errors:

    func f1() {
        
        // okay
        let a = MyClass<Int>()
        
        // okay
        var b: MyClass = a
    }

However I cannot use MyClass for a operate argument:

    // construct error: Reference to generic sort 'MyClass' requires arguments in <...>. Insert '<Any>'.
    func f2(c: MyClass) {
    }

I modified the code as Xcode suggests. And the error disappeared:

    // okay
    func f3(c: MyClass<Any>) {
    }

However I am unable to cross a object of MyClass<Int> to this operate:

    func f4() {
        // okay
        let a = MyClass<Int>()
        
        // construct error: Can't convert worth of sort 'MyClass<Int>' to anticipated argument sort 'MyClass<Any>'
        f3(c: a)
    }

Why cannot I exploit MyClass for a operate argument?

And why does not MyClass<Any> settle for MyClass<Int>?

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles