WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: day 16 - why function arguments not used within its body?

Forums > 100 Days of Swift

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return pictures.count

1) hi, normally, function parameter values are used within its body, but the above function parameter values, "tableView" and section", are not used within its body. What is the purpose of putting those function arguments when its not used within its body?

from lesson: As promised, the next thing to come is tableView: UITableView, which is the table view that triggered the code.

2) I don't understand how putting parameter values can trigger the code without being used in the function.


Those parameters have to be there in order to satisfy the data source method callback. You don't have to use them, but if they aren't there then UIKit won't recognize that you have that function defined and call it when it needs to.

Basically, the UITableViewDataSource protocol has a number of methods, some required and some optional, that get called by the system at certain times. By default, most (if not all; I'm too lazy to actually check) of the optional ones do nothing or have simple defaults but you can override them to provide custom behavior for your app. The required methods are, well, required for you to override. You have to match the function declaration exactly in order to override them, so even if you don't need those parameters, you have to include them or you'll be creating a new function instead of overriding an existing one. And the system won't know to call your new function so the behavior won't be what you want.

This is called the delegate pattern, which is used all over the place in UIKit. You'll become quite familiar with it as you progress in your learning. SwiftUI doesn't use it, so that'll be one difference to know when/if you decide to move in that direction.


Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.