Constraint a generic place holder to other generic place holder

I want to constraint U to T, is it possible?

protocol Pro {}
struct ST<T: Pro, AnyObject> {
    var anArr = [T]()
}

I know I can:

extension ST {
    // work
    func anElmFromArr<U: Pro>(at index: Int) -> U? {
        return anArr[index] as? U
    }
}

But I want to constraint like this:

extension ST {
    // doesn't work.
    func anElmFromArr<U: T>(at index: Int) -> U? {
        return anArr[index] as? U
    }

    // it also doesn't work.
    func anElmFromArr<U>(at index: Int) -> U? where U: T {
        return anArr[index] as? U
    }
}

Why not use T itself?

extension ST {
  func anElmFromArr(at index: Int, elmType: T) -> T? {
    return anArr[index]
  }
}

(Note you'll want to check the index to make sure the array has that many elements if you want to return an optional indicating that the element was there or not at said index.)

Because the array’s element is subclass of T
So, I want to cast back

Sorry, the code was wrong, I just adjusted it

Terms of Service

Privacy Policy

Cookie Policy