Menu
CoddyTech

Extensions Add Behavior

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

C adds helper functions around existing types rather than defining extension members on those types. Swift extensions can add methods, computed properties and protocol conformances without subclassing. They do not turn a value type into a reference type or modify its stored representation.

The C helper renders a Boolean flag, while Swift attaches a computed cliFlag property to Bool. Its result depends entirely on self. An extension cannot add stored instance properties, so stateful behavior needs existing storage or a separately designed container.

C: complete program

main.c

#include <stdio.h>
#include <stdbool.h>
static const char *cli_flag(bool enabled) { return enabled ? "--enabled" : "--disabled"; }
int main(void) { puts(cli_flag(true)); return 0; }

Swift: complete program

Bool.swift

import Foundation
extension Bool {
    var cliFlag: String { self ? "--enabled" : "--disabled" }
}

main.swift

import Foundation
print(true.cliFlag)

An extension is not a subclass and cannot override existing methods. Choose attached behavior when it makes the intended API clearer.

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 C Developers

Practice on your own: Swift playground