5 ms·
One way in which Swift is higher-level is in its support for dynamic constructs. For example, Swift allows you to dynamically check protocol conformance (e.g. i
by millstone 10y ago
One way in which Swift is higher-level is in its support for dynamic constructs. For example, Swift allows you to dynamically check protocol conformance (e.g. in generics). I believe Rust does not allow this.
- Manishearth 10y ago> Swift allows you to dynamically check protocol conformance (e.g. in generics) Could you explain more? Do you mean that Swift lets you arbitrarily downcast between protocol objects? I think Rust lets you do this too to some degree with Any. We generally stick to static bounds, though. I'd love to see if swift does something extra, and if it would be possible to add to Rust.
- millstone 10y agoYou 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!