UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

3      

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.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.