4 ms·
You can cast in any direction amongst protocol objects, concrete types, and generic types. You can also dynamically inspect the type itself (without needing an
by millstone 10y ago
You can cast in any direction amongst protocol objects, concrete types, and generic types. You can also dynamically inspect the type itself (without needing an instance of it).
For example, say we wish to write a function that builds an array from an arbitrary sequence. But as a fast path, if the sequence is already an array, just return it:
func makeArray<T:SequenceType>(from values:T) -> [T.Generator.Element] {
if let alreadyAnArray = values as? [T.Generator.Element] {
return alreadyAnArray
} else {
return Array(values)
}
}
or we can use a Golang-style technique to dispatch to a more specific protocol. See for example how debug descriptions are generated by checking conformance to a series of protocols in turn [1]: https://github.com/apple/swift/blob/1e2d192b61c9003d8b8a8593c2ef0fa6a524b8c0/stdlib/public/core/OutputStream.swift#L375 https://github.com/apple/swift/blob/1e2d192b61c9003d8b8a8593...
My understanding is that this is more limited in Rust, though I'm not too familiar with how Any works - please correct if I'm wrong.
- Manishearth 10y agoWith Any you can downcast to concrete types, but not to other trait objects. There is no fundamental reason why this shouldn't be allowed AFAICT though, so we might be able to add it. You can currently double-box things to do it, and probably write a library that makes this easy, but it's much nicer to have the language do it efficiently in cases like this. I wasn't aware that you could do that in swift, that sounds quite powerful and useful!