0
0
Swiftprogramming~5 mins

Where clauses for complex constraints in Swift

Choose your learning style9 modes available
Introduction

Where clauses help you add extra rules to your code, making it only work when certain conditions are true. This keeps your code safe and clear.

When you want a function to work only with certain types that meet specific rules.
When you want to filter items in a loop based on multiple conditions.
When you want to add extra checks to generic types in your code.
When you want to make your code easier to read by grouping conditions clearly.
Syntax
Swift
func functionName<T>(parameter: T) where T: Protocol, T: AnotherProtocol {
    // code here
}

for item in collection where item.property == value {
    // code here
}

The where keyword adds extra conditions to generics or loops.

You can combine multiple constraints separated by commas.

Examples
This function prints elements only if they can be described as text.
Swift
func printElements<T: Collection>(of collection: T) where T.Element: CustomStringConvertible {
    for element in collection {
        print(element.description)
    }
}
This loop prints only even numbers from the list.
Swift
for number in numbers where number % 2 == 0 {
    print(number)
}
This function compares two values only if they are the same type and can be compared.
Swift
func compare<T: Comparable, U: Comparable>(a: T, b: U) where T == U, T: Equatable {
    print(a == b)
}
Sample Program

This program uses a where clause to make sure the function only accepts collections of Person that can be described as text. It then prints a birthday message for each person.

Swift
struct Person {
    let name: String
    let age: Int
}

func celebrateBirthday<T: Collection>(for people: T) where T.Element == Person, T.Element: CustomStringConvertible {
    for person in people {
        print("Happy Birthday, \(person.description)!")
    }
}

extension Person: CustomStringConvertible {
    var description: String {
        "\(name), age \(age)"
    }
}

let friends = [Person(name: "Anna", age: 30), Person(name: "Ben", age: 25)]
celebrateBirthday(for: friends)
OutputSuccess
Important Notes

Where clauses make your code safer by adding clear rules.

You can use where clauses in functions, loops, and extensions.

Using where clauses helps others understand your code better.

Summary

Where clauses add extra conditions to your code.

They work well with generics and loops.

They make your code safer and easier to read.