carlhung
(Carlhung)
1
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
}
}
Alejandro
(Alejandro Alonso)
2
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.)
carlhung
(Carlhung)
3
Because the array’s element is subclass of T
So, I want to cast back
carlhung
(Carlhung)
4
Sorry, the code was wrong, I just adjusted it