Menu
CoddyTech

Extensions Add Behavior

Lesson 34 of 48 in Coddy's Swift for PHP Developers course.

PHP can put a derived operation around an integer in a helper function. Traits reuse methods in classes that opt into them, but do not install a computed property on every existing integer value. This free function keeps the operation local without changing runtime-wide behavior.

A Swift extension adds methods, computed properties or protocol conformance to an existing type. It cannot add stored instance properties or override existing behavior. The extension still follows access rules, and files needing imported APIs must include their own imports.

The target extension exposes the same calculation as Int.parity. It derives a result rather than storing extra state. For the String task, choose the required character predicate separately instead of assuming this number example supplies the task algorithm.

Complete PHP comparison program:

<?php
declare(strict_types=1);
function parity(int $number): string { return $number % 2 === 0 ? "even" : "odd"; }
echo parity(8), "\n", parity(5), "\n";

Complete Swift comparison program, compiled from these files:

Int.swift

extension Int {
    var parity: String { self % 2 == 0 ? "even" : "odd" }
}

main.swift

print(8.parity)
print(5.parity)
challenge icon

Challenge

Easy

Add computed String.asciiVowels: Int in a String extension in String.swift. Count ASCII vowels in either case, with duplicates. Input is a line of 0 through 80 ASCII letters and spaces. Output the count. Nonvowels contribute zero.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in String.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return "Orange".asciiVowels == 3 && "AEe".asciiVowels == 3 && "xyz".asciiVowels == 0
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for PHP Developers

Practice on your own: Swift playground