Member-only story

Swift Programming Tutorial: Self-Requirements

Learn how to quickly set high standards in your protocol

Arc Sosangyo
4 min readDec 4, 2024
Photo by Carlos Felipe Ramírez Mesa on Unsplash

Let’s tackle about self-requirements in Swift — a feature that lets your protocols act like that one friend who insists on their friends being into the same nerdy hobbies. Think Dungeons & Dragons meets software engineering. They’re a way to say, “Sure, I’ll let you hang out with me (or, you know, conform to this protocol), but only if you meet these specific criteria.”

If protocols are like blueprints for your code, self-requirements are the “Terms & Conditions” section. But instead of boring legalese, Swift gets straight to the point: you can only join this protocol party if your type is also a subclass of a particular class, conforms to another protocol, or both. It’s an elegant way to enforce constraints and keep things clean.

Let’s dive into the why, the how, and some code-packed examples that’ll make you feel like you just rolled a nat 20 in your Swift campaign.

This article is part of my Swift Programming Tutorial series.

The Problem: Loose Standards

Imagine you’re designing a protocol for something heroic, like slaying dragons:

protocol DragonSlayer {
func slayDragon() -> String
}

--

--

Arc Sosangyo
Arc Sosangyo

Written by Arc Sosangyo

Arc is an iOS Dev and app publisher, a former IT manager who transitioned to iOS engineering, and a big fan of AI, coding, science, history, and philosophy.

Responses (1)