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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With