ios - Swift: function overload resolution via closure parameter? -
i trying solve separate problem related parsing json. in process, ran afoul of swift compiler, expected use closure template arguments select function overload optional types.
i haven't seen explicit in documentation on topic, not expectation else equal, swiftc use arguments of closure parameter in generic function select correct overload?
here simplest sample come with:
import foundation let os:nsstring = "foo!" let d:[string:anyobject] = ["a": os] struct model { var opt:string? var basic:string = "" } func read<t>(source:anyobject?, set:t -> ()) { if let t:t = source as? t { println("basic: read type: \(t.self) value \(source)") } else { println("failed read basic type \(t.self) value \(source)") } } func read<t>(source:anyobject?, set:t? -> ()) { assert(false, "this not called") if let t:t? = source as? t? { println("optional: read optional type: \(t.self) value \(source)") } else { println("failed read optional type \(t.self) value \(source)") } } var m = model() println(m) let raw: anyobject? = d["a"] struct property<t> { typealias v = t var get:() -> t var set:t -> () func doread(d:[string:anyobject]) { read(d["a"], set) } } let b = property(get: { m.basic }, set: { v in m.basic = v }) b.doread(d) let o = property(get: { m.opt }, set: { v in m.opt = v }) o.doread(d)
per comment inline, expected second overload used optional types, not. missing something?
edit
note compiler inferring optional / non optional type property construct - knows closure takes optional, doesn't select overload. have restored of original logging code above, , output is:
basic: read type: swift.string value optional(foo!)
failed read basic type swift.optional value optional(foo!)
from usage of swift, see compiler prefers non-optionals on optionals. operation:
let o = property(set: { v in m.opt = v })
is legal when v
non-optional, , therefore compiler assumes such.
this question, , assume lot of other questions answered when swift made open-source.
Comments
Post a Comment