Extensions Add Behavior
Lesson 34 of 48 in Coddy's Swift for Rust Developers course.
Rust can add extension-style methods to a foreign type by defining a local trait and implementing it for that type. Coherence rules restrict which trait/type combinations may be implemented, and the trait must be available for method lookup. Swift extensions can directly add methods, computed properties and conformances to an existing type without subclassing it. They cannot add stored instance properties or override existing behavior. Both examples derive parity from the integer without new stored state. Keep extension scope, naming conflicts and access rules in mind instead of assuming a Rust inherent implementation can be added to any foreign type.
Rust
trait Parity { fn is_even(&self) -> bool; }
impl Parity for i32 { fn is_even(&self) -> bool { self % 2 == 0 } }
fn main() {
println!("{}", 8_i32.is_even());
println!("{}", 9_i32.is_even());
}
Swift
extension Int {
var isEven: Bool { self % 2 == 0 }
}
print(8.isEven)
print(9.isEven)Challenge
EasyAdd 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Rust Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps7Failures and Abstraction
Throwing Functions and CatchResult as a Stored OutcomeProtocols and ConformanceExtensions Add BehaviorGeneric Value ContainersRecap: Validated Batch2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground