Can't extend closure in Swift? -


flush excitement extending bool, thought fun extend closures in swift (we did no fuss @ in smalltalk, why not?).

here's playground:

typealias niladicclosure = () -> ()  extension niladicclosure {     var theanswertolife:int {         return 42     } }  let block:niladicclosure = {}  block.theanswertolife 

it doesn't work, saying niladicclosure not have member named 'theanswertolife'. looking in console, bit more information:

playground execution failed: /var/folders/2k/6y8rslzn1m95gjpg534j7v8jzr03tz/t/./lldb/33726/playground119.swift:3:1: error: non-nominal type 'niladicclosure' cannot extended extension niladicclosure { ^         ~~~~~~~~~~~~~~ 

what non-nominal type? there pattern/workaround?

other similar questions predated swift 2, specific enough people offered workarounds specific extension. i'm interested in whether swift closures first class objects can add additional behavior to, other things in swift.

what non-nominal type?

a nominal type type explicit name. non-nominal type type without such name, () -> (). compound types, including closures , tuples (such (int, string)) cannot extended.

is there pattern/workaround?

you use composition instead of extensions, perhaps using swift 2's new protocol features:

typealias niladicclosure = () -> ()  protocol niladicclosureprotocol {     var someclosure : niladicclosure? {get} }  protocol sorryfortheinconvenience {     var theanswertolife : int {get} }  extension sorryfortheinconvenience {     var theanswertolife : int {         return 42     } }  struct somethingawesome : niladicclosureprotocol, sorryfortheinconvenience {     var someclosure : niladicclosure? }  let foo = somethingawesome() foo.theanswertolife // 42 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -