[swift-users] still wrestling with a type conversion problem
David Baraff
davidbaraff at gmail.com
Tue Jul 4 20:09:16 CDT 2017
> On Jul 4, 2017, at 5:48 PM, Jacob Bandes-Storch <jtbandes at gmail.com> wrote:
>
> On Tue, Jul 4, 2017 at 7:21 AM, David Baraff <davidbaraff at gmail.com <mailto:davidbaraff at gmail.com>> wrote:
>
> func decoded(_ input: Any) -> Set {
> if let listVal = input as? [Set.Element] {
> return Set(listVal)
> }
> return self
> }
>
>
> This looks a little weird — what is `self` here? It might be more appropriate to use a `static func` or even a failable `init?`.
Yes, it is weird. What’s going on is this: we invoke the decoded function in the protocol by writing
defaultValue.decoded(someObscureAny)
in this case, we’re saying “take my Any, and give me back the same type of thing as defaultValue, but if you can’t, then give me back defaultValue”. So now you’ve imparted the type information of defaultValue to be able to call the correct function. And i agree this is strange. i’d much rather have
static func decoded(_ input:Any, defaultValue:Set) -> Set {
}
but when I tried that, I got a compiler error about needing to do something which has type constraints. I think a static function in the protocol doesn’t lock things down enough?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170704/a7d62f0d/attachment.html>
More information about the swift-users
mailing list