Swift Examples
Dave Braunschweig
Strings
// This program demonstrates string functions. import Foundation func main() { let string:String = "Hello" print("string: " + string) print("string.lowercased(): " + string.lowercased()) print("string.uppercased(): " + string.uppercased()) print("find(string, \"e\"): " + String(find(string:string, character:"e"))) print("string.count: " + String(string.count)) print("string.replacingOccurrences(of:\"H\", with:\"j\"): " + string.replacingOccurrences(of:"H", with:"j")) print("string.reversed(): " + String(string.reversed())) print("substring(2, 2): " + substring(string:string, start:2, length:2)) print("string.trimmingCharacters(\"H\"): " + string.trimmingCharacters(in:CharacterSet.init(charactersIn: "H"))) let name:String = "Bob" let value:Double = 123.456 print("\(name) earned $" + String(format:"%.2f", value)) } func find(string:String, character:Character) -> Int { var result: Int if let index = string.firstIndex(of:character) { result = string.distance(from: string.startIndex, to: index) } else { result = -1 } return result } func substring(string:String, start:Int, length:Int) -> String { let startIndex = string.index(string.startIndex, offsetBy: start) let endIndex = string.index(string.startIndex, offsetBy: start + length - 1) return String(string[startIndex...endIndex]) } main()
Output
string: Hello string.lowercased(): hello string.uppercased(): HELLO find(string, "e"): 1 string.count: 5 string.replacingOccurrences(of:"H", with:"j"): jello string.reversed(): olleH substring(2, 2): ll string.trimmingCharacters("H"): ello Bob earned $123.46
Files
// This program demonstrates reading a text file with exception handling. // References: // https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html import Foundation func readFile(filename:String) { var text = "" do { text = try String(contentsOfFile: filename, encoding: .utf8) let lines = text.components(separatedBy:"\n") for line in lines { print(line) } } catch { print("Error reading " + filename) print(error.localizedDescription) } } func main() { let filename:String = "temperature.txt" readFile(filename:filename) } main()
Output
Celsius,Fahrenheit 0,32 10,50 20,68 ... 80,176 90,194 100,212