FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

What is a protocol?

Swift version: 5.4

Paul Hudson    @twostraws   

A protocol is a collection of methods that describe a specific set of similar actions or behaviors. I realize that probably didn't help much, so I'll try to rephrase in more detail: how many rows should a table view have? How many sections? What should the section titles be? Can the user move rows? If so, what should happen when they do?

All those questions concern a similar thing: data going into a UITableView. As a result, they all go into a single protocol, called UITableViewDataSource. Some of the behaviors inside that protocol are optional. For example, canEditRowAt is optional and defaults to true if you don't provide a value yourself.

When you work in Swift you will frequently have to make your class conform to a protocol. This is done by adding the protocol name to your class definition, then filling in any required methods, like this:

class ViewController: UIViewController, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // request 10 rows
        return 10

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // return a dummy table view cell; your own code should use prototype cells or similar
        return UITableViewCell()

When you do that – when you promise Swift that your class conforms to a protocol – you can be darn sure it checks to make sure you're right. And that means it will refuse to build your code if you haven't added support for all the required methods, which is a helpful security measure.

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.

Learn more

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

Available from iOS 2.0 – see Hacking with Swift tutorial 1

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.