Menu
CoddyTech

Extensions Add Behavior

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

Go permits methods on a locally defined receiver type, but cannot add methods directly to a nonlocal type or a built-in type such as bool. This source defines Flag with bool as its underlying type. Swift can extend Bool itself with added behavior.

Swift extensions add methods, computed properties or protocol conformances without subclassing. They cannot add stored instance properties. The target property derives its command-line flag from self, while Go exposes the same behavior as a method on its defined wrapper type.

Go: complete program

main.go

package main
import (
    "fmt"
)
type Flag bool
func (flag Flag) CLIFlag() string { if flag { return "--enabled" }; return "--disabled" }

func main() {
fmt.Println(Flag(true).CLIFlag())
}

Swift: complete program

Bool.swift

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

main.swift

import Foundation
print(true.cliFlag)

An extension cannot override existing methods. Decide whether adapting a helper into type-attached behavior makes the interface clearer rather than assuming source method rules are identical.

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

Practice on your own: Swift playground