[swift-users] still wrestling with a type conversion problem
David Baraff
davidbaraff at gmail.com
Wed Jul 5 10:42:38 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?`.
I figure out how to do this right. Something like:
protocol DecodableFromAny {
static func fromAny(_ payload:Any) -> Self?
}
extension Array : DecodableFromAny {
static func fromAny(_ payload: Any) -> Array? {
if let x = payload as? [Array.Element] {
return x
}
return nil
}
}
func decodeMe<T>(_ payload:Any) -> T? {
if let dt = T.self as? DecodableFromAny {
return type(of: dt).fromAny(payload) as! T
} else {
return payload as? T
}
}
I got tripped up not realizing I could cast “T.self” to the protocol, and then call it once i invoked type(of:) on that. much much nicer this way.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170705/6aea3a5f/attachment.html>
More information about the swift-users
mailing list