Selector with Default Parameter Value
I found a strange behavior in #selector
with Default Parameter Values.
I set UIRefreshControl
as usual like this.
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(loadItems), forControlEvents: .ValueChanged)
...
In this same file, I have a function that takes a default parameter value.
func loadItems(page: Int = 0) {
debugPrint("\(page)") // Need it later
// Load items from API...
}
I wanted to use the default parameter value if users use pullToRefresh action. I did pullToRefresh action several times, and then I could see the logs like this.
// This is a Xcode console.
> 0
> 140622637638640
> 0
Why is 140622637638640
? I expect to see 0
same as the first. Finally, I avoided having this strange behavior by adding another function.
override func viewDidLoad() {
super.viewDidLoad()
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(pullToRefreshed), forControlEvents: .ValueChanged)
...
}
...
func pullToRefreshed {
loadItems()
}
func loadItems(page: Int = 0) {
// Here is debugPring(\(page))
// load items from API...
}
I think it’s easy to avoid this bug, but it looks weird for me. I don’t want to create a function for only that. If you know about that, tell me about it. May be someone already mentioned the above. If not, I may file a bug report in JIRA.