In the following code, I want to test if x is a `SpecialController`. If it is, I want to get the `currentValue` as a `SpecialValue`. How do you do this? If not with a cast, then some other technique.
I understand the error, and that SpecialController by itself is not a simple type to cast to. But it seems like what I’m saying is logically consistent and not that complicated. Is there really no way to *say* it in Swift?
protocol SpecialController {
associated type SpecialValueType : SpecialValue
var currentValue: SpecialValueType? { get }
}
...
var x: AnyObject = ...
if let sc = x as? SpecialController { // does not compile
The only real way to do this today is to have two layers of protocol:
protocol SpecialControllerBase {
var currentValueBase: SpecialValue? { get }
}
protocol SpecialController: SpecialControllerBase {
associatedtype SpecialValueType : SpecialValue
var currentValue: SpecialValueType? { get }
}
extension SpecialController {
var currentValueBase: SpecialValue? { return self.currentValue }
}
Supporting this natively is the feature called generalized existentials, described in the “Generics Manifesto <https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#generalized-existentials>” of potential future Swift features. This has a lot of design and implementation considerations, so it’s not planned to happen right away, but it’s definitely a heavily-requested feature.
Jordan
···
On Nov 2, 2016, at 12:31, Robert Nikander via swift-users <swift-users@swift.org> wrote:
Hi,
In the following code, I want to test if x is a `SpecialController`. If it is, I want to get the `currentValue` as a `SpecialValue`. How do you do this? If not with a cast, then some other technique.
I understand the error, and that SpecialController by itself is not a simple type to cast to. But it seems like what I’m saying is logically consistent and not that complicated. Is there really no way to *say* it in Swift?
protocol SpecialController {
associated type SpecialValueType : SpecialValue
var currentValue: SpecialValueType? { get }
}
...
var x: AnyObject = ...
if let sc = x as? SpecialController { // does not compile