Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a closure from an array

Tags:

swift

Removing a closure from an array but not using it causes compiler error "Expression resolves to an unused function". Is there a good way to avoid this, other than assigning the function to a throwaway variable?

typealias StringFunction = () -> String  
var list = [StringFunction]()            
list.append({ "Hello World!" })          
let hi = list[0]()                       // "Hello World!"
list.removeAtIndex(0)                    // Expression resolves to an unused function
let _ = list.removeAtIndex(0)            // Works
like image 438
Blixt Avatar asked Jun 03 '15 16:06

Blixt


1 Answers

Assigning the result of the expression to a throwaway variable is the correct way to do that. In fact, this is the idiomatic way to treat unused results in Swift.

Hence (as noted in the comments of another answer) the correct solution the is:

typealias StringFunction = () -> String
var list = [StringFunction]()
list.append({ "Hello World!" })
let hi = list[0]()
_ = list.remove(at: 0) // Note there's no need for `let`

Doing so not only makes your code clearer about your intent (i.e. it indicates that you definitely don't need the result of the method), but also helps the compiler perform all sorts of useful optimizations.

like image 182
Alvae Avatar answered Nov 13 '22 03:11

Alvae