struct User { | |
let id: Int | |
let name: String | |
let email: String? | |
} | |
extension User: JSONDecodable { | |
static func create(id: Int, name: String, email: String?) -> User { | |
return User(id: id, name: name, email: email) | |
} | |
static func decode(json: JSONValue) { | |
return check(User.create, json["id"], json["name"], json["email"]) | |
// check() calls its fn only if the required arguments are non-nil | |
// You could readily define check() as an infix operator that takes a tuple, e.g.: | |
// return User.create?<(json["id"], json["name"], json["email"]) | |
} | |
} | |
protocol JSONDecodeable { | |
class func decode(json: JSONValue) -> Self? | |
} | |
enum JSONValue { | |
case JSONObject([String: JSONValue]) | |
case JSONArray([JSONValue]) | |
// etc | |
subscript(key: String) -> Int {} | |
subscript(key: String) -> Bool {} | |
// etc | |
} | |
func check<A, B, C, R>(fn: (A,B,C) -> R, a: A?, b: B?, c: C?) -> R? { | |
if a == nil || b == nil || c == nil { | |
return nil | |
} else { | |
return fn(a!, b!, c!) | |
} | |
} | |
func check<A, B, C, R>(fn: (A?,B,C) -> R, a: A?, b: B?, c: C?) -> R? { | |
if b == nil || c == nil { | |
return nil | |
} else { | |
return fn(a, b!, c!) | |
} | |
} | |
func check<A, B, C, R>(fn: (A,B?,C) -> R, a: A?, b: B?, c: C?) -> R? { | |
if a == nil || c == nil { | |
return nil | |
} else { | |
return fn(a!, b, c!) | |
} | |
} | |
func check<A, B, C, R>(fn: (A,B,C?) -> R, a: A?, b: B?, c: C?) -> R? { | |
if a == nil || b == nil { | |
return nil | |
} else { | |
return fn(a!, b!, c) | |
} | |
} | |
func check<A, B, C, R>(fn: (A?,B?,C) -> R, a: A?, b: B?, c: C?) -> R? { | |
if c == nil { | |
return nil | |
} else { | |
return fn(a, b, c!) | |
} | |
} | |
func check<A, B, C, R>(fn: (A?,B,C?) -> R, a: A?, b: B?, c: C?) -> R? { | |
if b == nil { | |
return nil | |
} else { | |
return fn(a, b!, c) | |
} | |
} | |
func check<A, B, C, R>(fn: (A,B?,C?) -> R, a: A?, b: B?, c: C?) -> R? { | |
if a == nil { | |
return nil | |
} else { | |
return fn(a!, b, c) | |
} | |
} | |
func check<A, B, C, R>(fn: (A?,B?,C?) -> R, a: A?, b: B?, c: C?) -> R? { | |
return fn(a, b, c) | |
} | |
// etc. |
This comment has been minimized.
This comment has been minimized.
You can do that using switch patterns. IIRC this should work now:
|
This comment has been minimized.
This comment has been minimized.
Eh, if all the check implementations are in a library, why do you care how many there are? |
This comment has been minimized.
This comment has been minimized.
@jckarter The compiler won't be able to determine which implementation of |
This comment has been minimized.
This comment has been minimized.
"Eh, if all the check implementations are in a library, why do you care how many there are?" That argument makes good practical sense, I guess it's just a deeply held 'code smell' prejudice against any time I start cutting and pasting code with minor variations each time. I agree that it's worth weighing the cost of each approach (custom operators vs. something like this). Sure, it's tedious to write this way the first time, but to new people picking up the code base, this will be highly readable and easy to understand quickly. I don't even have to read past the first few overloads before I'm comfortable saying "Got it! Moving on" The delicious custom operators are undoubtably 'far more expensive' for readability with new devs, even if they are more personally rewarding to understand. I guess the end result in actual client code that calls this stuff is more or less the same syntactic simplicity with either approach, so as a cost/benefit discussion in a professional engineering shop, I can definitely see this pragmatic approach winning out. |
This comment has been minimized.
This comment has been minimized.
Yeah, the intent is not that developers would read these combinatoric overloads. They can even be machine-generated. The result is ugly—I agree—but not that different from e.g. this ugliness in Haskell: https://hackage.haskell.org/package/aeson-0.8.0.2/docs/Data-Aeson-Types.html#t:FromJSON |
This comment has been minimized.
This comment has been minimized.
I think it's worth remembering that all of this is to avoid the following:
(I usually use I fear we're falling into a pit of creating lot of complexity to avoid a small amount of complexity. Is it really worth it in today's Swift? I'm not saying that there aren't some things the Swift language could change to make all of this more beautiful, but is the above Take this to another level and try adding some error handling to both your example and mine. What code do I need to add so I could return a useful The key simplification is factoring all this if-let-if-let into a single function that returns an optional. Once we did that (and we're all doing that), I am beginning to believe that further simplification is counter-productive (I'm even starting to question my own contributions here.) All the examples around this are in JSON parsing. Maybe we just accept that JSON parsing uses a lot of if-let, and make sure to parse JSON into structs in one place so that doesn't bother other code. We should be doing that anyway. |
This comment has been minimized.
This comment has been minimized.
That's a totally fair point, @rnapier! My current production project has the kind of code you wrote there, and it's honestly not that bad.
I actually think |
This comment has been minimized.
This comment has been minimized.
You know, if you bring error handling into the mix, and start requiring |
This comment has been minimized.
This comment has been minimized.
I was just experimenting with exactly this question :D I've been working extensively with an Note that these use an
But here's what the code looks like without that:
It's not quite as beautiful, but I don't think it's horrible (the
(I still prefer adding flatMap to Optional.) That said, when I tried to rewrite my So the nice thing about |
This comment has been minimized.
This comment has been minimized.
The problem with code that takes an We can implement enum Result<T> {
case Value(T)
case Error(NSError)
}
extension Result {
func flatMap<U>(f: T -> Result<U>) -> Result<U> {
switch (self) {
case let Value(value):
return f(value)
case let Error(error):
return Result<U>.Error(error)
}
}
}
func pagesFromOpenSearchData(data: NSData) -> Result<[Page]> {
let pages = asJSON(data)
.flatMap { asJSONArray($0) }
.flatMap { atIndex($0, 1) }
.flatMap { asStringList($0) }
.flatMap { asPages($0) }
return pages
} |
This comment has been minimized.
This comment has been minimized.
Hello, Just a quick note to tell you that for checks up to n parameters there are 2^1 + 2^2 + 2^3+....+2^(n-1)+2^n distinct combinations. I will just say(without going in to the details about how I found out) that the current Swift compiler is not really up to the task. I believe that it might be a good approach for very practical reasons but unfortunately it is un-feasable (today?). What might work is to use check functions up to 4-5 parameters and handle the rest manually. What is interesting to me is the very declarative style and lack of voodoo to make the mapping work. It looks to me really easy to debug. Even more interesting is the error handling version which could produce very precise error messages so one doesn't need anymore to trace the code in order to understand errors. Adrian |
This comment has been minimized.
Thinking about it further (from Twitter), I’d be happy if this worked as needed:
Of course, making it a statement and having all the types inferred is nicer, but probably not (2^(n + 1) − 1, for n = maximum allowed number of arguments) implementations of
check()
nicer.