Extensions
extension String { ... } adds a new method directly onto Swift's own built-in String type — one you didn't write and can't modify, and one that's a struct anyway, so it couldn't be subclassed even if you wanted to. Inside the extension, self refers to the specific String instance the method was called on.
Main.swift
Try it yourself →extension String {
func shout() -> String {
return self.uppercased() + "!"
}
}
print("hello".shout())Output
HELLO!
Next: generics — writing one struct that works across many types, with the compiler still checking type safety.
Practice exercise
Write an extension on Int that adds a method isEven() -> Bool returning whether self is divisible by 2, then print 4.isEven().