2014-06-04 11:50:17 +04:00
---
language: swift
contributors:
- ["Grant Timmerman", "http://github.com/grant"]
2014-08-24 07:48:10 +04:00
- ["Christopher Bess", "http://github.com/cbess"]
2015-10-08 06:11:24 +03:00
- ["Joey Huang", "http://github.com/kamidox"]
2015-08-04 06:11:44 +03:00
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
2015-10-07 06:00:11 +03:00
- ["Clayton Walker", "https://github.com/cwalk"]
2015-11-01 03:48:44 +03:00
- ["Fernando Valverde", "http://visualcosita.xyz"]
2016-10-08 12:59:20 +03:00
- ["Alexey Nazaroff", "https://github.com/rogaven"]
2019-08-03 14:13:22 +03:00
- ["@Samasaur1", "https://github.com/Samasaur1"]
2014-06-04 11:50:17 +04:00
filename: learnswift.swift
---
2021-05-25 14:42:50 +03:00
Swift is a programming language for iOS and macOS development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+.
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
The official _[Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329)_ book from Apple is now available via iBooks. It goes into much more detail than this guide, and if you have the time and patience to read it, it's recommended. Some of these examples are from that book.
2014-08-25 03:33:16 +04:00
2018-10-12 00:21:54 +03:00
Another great reference is _About Swift_ on Swift's [website ](https://docs.swift.org/swift-book/ ).
2014-06-04 11:50:17 +04:00
2014-09-08 15:08:28 +04:00
```swift
2014-10-04 21:08:23 +04:00
// import a module
2019-08-03 14:13:22 +03:00
import Foundation
2014-10-04 21:08:23 +04:00
2019-08-03 14:13:22 +03:00
// Single-line comments are prefixed with //
// Multi-line comments start with /* and end with */
/* Nested multiline comments
/* ARE */
allowed
*/
2014-06-05 00:22:01 +04:00
2014-08-24 23:37:09 +04:00
// Xcode supports landmarks to annotate your code and lists them in the jump bar
// MARK: Section mark
2015-11-01 03:48:44 +03:00
// MARK: - Section mark with a separator line
2014-08-24 23:37:09 +04:00
// TODO: Do something soon
2014-12-14 05:01:08 +03:00
// FIXME: Fix this code
2014-08-24 23:37:09 +04:00
2019-08-03 14:13:22 +03:00
//MARK: Hello, World
// From Swift 3 on, to print, just use the `print` method.
// It automatically appends a new line.
print("Hello, world")
//
// MARK: - Variables
//
//Use `let` to declare a constant and `var` to declare a variable.
let theAnswer = 42
var theQuestion = "What is the Answer?"
theQuestion = "How many roads must a man walk down?"
theQuestion = "What is six by nine?"
// Atttempting to reassign a constant throws a compile-time error
//theAnswer = 54
// Both variables and constants can be declared before they are given a value,
// but must be given a value before they are used
let someConstant: Int
var someVariable: String
// These lines will throw errors:
//print(someConstant)
//print(someVariable)
someConstant = 0
someVariable = "0"
2019-08-03 17:38:55 +03:00
// These lines are now valid:
print(someConstant)
print(someVariable)
2019-08-03 14:13:22 +03:00
// As you can see above, variable types are automatically inferred.
// To explicitly declare the type, write it after the variable name,
// separated by a colon.
let aString: String = "A string"
let aDouble: Double = 0
// Values are never implicitly converted to another type.
// Explicitly make instances of the desired type.
let stringWithDouble = aString + String(aDouble)
let intFromDouble = Int(aDouble)
// For strings, use string interpolation
let descriptionString = "The value of aDouble is \(aDouble)"
// You can put any expression inside string interpolation.
let equation = "Six by nine is \(6 * 9), not 42!"
// To avoid escaping double quotes and backslashes, change the string delimiter
let explanationString = #"The string I used was "The value of aDouble is \(aDouble)" and the result was \#(descriptionString)"#
// You can put as many number signs as you want before the opening quote,
// just match them at the ending quote. They also change the escape character
// to a backslash followed by the same number of number signs.
let multiLineString = """
This is a multi-line string.
It's called that because it takes up multiple lines (wow!)
Any indentation beyond the closing quotation marks is kept, the rest is discarded.
2019-10-22 10:10:07 +03:00
You can include " or "" in multi-line strings because the delimiter is three "s.
2019-08-03 14:13:22 +03:00
"""
// Arrays
let shoppingList = ["catfish", "water", "tulips",] //commas are allowed after the last element
let secondElement = shoppingList[1] // Arrays are 0-indexed
// Arrays declared with let are immutable; the following line throws a compile-time error
//shoppingList[2] = "mango"
// Arrays are structs (more on that later), so this creates a copy instead of referencing the same object
var mutableShoppingList = shoppingList
mutableShoppingList[2] = "mango"
// == is equality
shoppingList == mutableShoppingList // false
// Dictionaries declared with let are also immutable
var occupations = [
"Malcolm": "Captain",
2019-08-03 17:38:55 +03:00
"Kaylee": "Mechanic"
2019-08-03 14:13:22 +03:00
]
occupations["Jayne"] = "Public Relations"
// Dictionaries are also structs, so this also creates a copy
let immutableOccupations = occupations
2014-08-24 07:48:10 +04:00
2019-08-03 14:13:22 +03:00
immutableOccupations == occupations // true
2014-10-18 06:22:28 +04:00
2019-08-03 14:13:22 +03:00
// Arrays and dictionaries both automatically grow as you add elements
mutableShoppingList.append("blue paint")
occupations["Tim"] = "CEO"
// They can both be set to empty
mutableShoppingList = []
occupations = [:]
let emptyArray = [String]()
let emptyArray2 = Array< String > () // same as above
// [T] is shorthand for Array< T >
let emptyArray3: [String] = [] // Declaring the type explicitly allows you to set it to an empty array
let emptyArray4: Array< String > = [] // same as above
// [Key: Value] is shorthand for Dictionary< Key , Value >
let emptyDictionary = [String: Double]()
let emptyDictionary2 = Dictionary< String , Double > () // same as above
var emptyMutableDictionary: [String: Double] = [:]
var explicitEmptyMutableDictionary: Dictionary< String , Double > = [:] // same as above
// MARK: Other variables
2014-08-25 03:33:16 +04:00
let øπΩ = "value" // unicode variable names
2019-08-03 14:13:22 +03:00
let 🤯 = "wow" // emoji variable names
2014-10-18 06:22:28 +04:00
2019-08-03 14:13:22 +03:00
// Keywords can be used as variable names
// These are contextual keywords that wouldn't be used now, so are allowed
let convenience = "keyword"
let weak = "another keyword"
let override = "another keyword"
2014-12-14 05:01:08 +03:00
2019-08-03 14:13:22 +03:00
// Using backticks allows keywords to be used as variable names even if they wouldn't be allowed normally
let `class` = "keyword"
// MARK: - Optionals
/*
Optionals are a Swift language feature that either contains a value,
or contains nil (no value) to indicate that a value is missing.
Nil is roughly equivalent to `null` in other languages.
A question mark (?) after the type marks the value as optional of that type.
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
If a type is not optional, it is guaranteed to have a value.
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
Because Swift requires every property to have a type, even nil must be
explicitly stored as an Optional value.
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
Optional< T > is an enum, with the cases .none (nil) and .some(T) (the value)
*/
2014-10-18 06:22:28 +04:00
2014-10-04 21:08:23 +04:00
var someOptionalString: String? = "optional" // Can be nil
2019-08-03 14:13:22 +03:00
// T? is shorthand for Optional< T > — ? is a postfix operator (syntax candy)
let someOptionalString2: Optional< String > = nil
let someOptionalString3 = String?.some("optional") // same as the first one
let someOptionalString4 = String?.none //nil
/*
To access the value of an optional that has a value, use the postfix
operator !, which force-unwraps it. Force-unwrapping is like saying, "I
2019-08-03 17:38:55 +03:00
know that this optional definitely has a value, please give it to me."
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
Trying to use ! to access a non-existent optional value triggers a
runtime error. Always make sure that an optional contains a non-nil
value before using ! to force-unwrap its value.
*/
2014-10-04 21:08:23 +04:00
if someOptionalString != nil {
// I am not nil
if someOptionalString!.hasPrefix("opt") {
2015-08-04 06:05:22 +03:00
print("has the prefix")
2014-10-04 21:08:23 +04:00
}
}
2019-08-03 14:13:22 +03:00
// Swift supports "optional chaining," which means that you can call functions
// or get properties of optional values and they are optionals of the appropriate type.
// You can even do this multiple times, hence the name "chaining."
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
let empty = someOptionalString?.isEmpty // Bool?
// if-let structure -
// if-let is a special structure in Swift that allows you to check
// if an Optional rhs holds a value, and if it does unwrap
// and assign it to the lhs.
if let someNonOptionalStringConstant = someOptionalString {
2014-10-18 06:22:28 +04:00
// has `Some` value, non-nil
2019-08-03 14:13:22 +03:00
// someOptionalStringConstant is of type String, not type String?
if !someNonOptionalStringConstant.hasPrefix("ok") {
2014-10-18 06:22:28 +04:00
// does not have the prefix
}
2014-10-04 21:08:23 +04:00
}
2019-08-03 14:13:22 +03:00
//if-var is allowed too!
if var someNonOptionalString = someOptionalString {
someNonOptionalString = "Non optional AND mutable"
print(someNonOptionalString)
}
2016-11-12 03:12:13 +03:00
2019-08-03 14:13:22 +03:00
// You can bind multiple optional values in one if-let statement.
// If any of the bound values are nil, the if statement does not execute.
if let first = someOptionalString, let second = someOptionalString2,
let third = someOptionalString3, let fourth = someOptionalString4 {
print("\(first), \(second), \(third), and \(fourth) are all not nil")
}
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
//if-let supports "," (comma) clauses, which can be used to
// enforce conditions on newly-bound optional values.
// Both the assignment and the "," clause must pass.
let someNumber: Int? = 7
if let num = someNumber, num > 3 {
print("num is not nil and is greater than 3")
}
2015-10-08 06:11:24 +03:00
2019-08-03 14:13:22 +03:00
// Implicitly unwrapped optional — An optional value that doesn't need to be unwrapped
let unwrappedString: String! = "Value is expected."
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
// Here's the difference:
let forcedString = someOptionalString! // requires an exclamation mark
let implicitString = unwrappedString // doesn't require an exclamation mark
2014-06-05 00:22:01 +04:00
2014-10-18 06:22:28 +04:00
/*
2019-08-03 14:13:22 +03:00
You can think of an implicitly unwrapped optional as giving permission
for the optional to be unwrapped automatically whenever it's used.
Rather than placing an exclamation mark after the optional's name each time you use it,
you place an exclamation mark after the optional's type when you declare it.
*/
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
// Otherwise, you can treat an implicitly unwrapped optional the same way the you treat a normal optional
// (i.e., if-let, != nil, etc.)
2014-06-05 00:22:01 +04:00
2019-08-03 14:13:22 +03:00
// Pre-Swift 5, T! was shorthand for ImplicitlyUnwrappedOptional< T >
// Swift 5 and later, using ImplicitlyUnwrappedOptional throws a compile-time error.
//var unwrappedString2: ImplicitlyUnwrappedOptional< String > = "Value is expected." //error
2015-11-11 02:03:40 +03:00
2019-08-03 14:13:22 +03:00
// The nil-coalescing operator ?? unwraps an optional if it contains a non-nil value, or returns a default value.
someOptionalString = nil
let someString = someOptionalString ?? "abc"
print(someString) // abc
// a ?? b is shorthand for a != nil ? a! : b
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
// MARK: - Control Flow
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
let condition = true
if condition { print("condition is true") } // can't omit the braces
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
if theAnswer > 50 {
print("theAnswer > 50")
} else if condition {
print("condition is true")
} else {
print("Neither are true")
2014-06-04 11:50:17 +04:00
}
2019-08-03 14:13:22 +03:00
// The condition in an `if` statement must be a `Bool` , so the following code is an error, not an implicit comparison to zero
//if 5 {
// print("5 is not zero")
//}
2014-06-04 11:50:17 +04:00
// Switch
2019-08-03 14:13:22 +03:00
// Must be exhaustive
// Does not implicitly fall through, use the fallthrough keyword
2014-12-14 05:01:08 +03:00
// Very powerful, think `if` statements with syntax candy
// They support String, object instances, and primitives (Int, Double, etc)
2014-06-04 11:50:17 +04:00
let vegetable = "red pepper"
2019-08-03 14:13:22 +03:00
let vegetableComment: String
2014-06-04 11:50:17 +04:00
switch vegetable {
case "celery":
2019-08-03 14:13:22 +03:00
vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress": // match multiple values
vegetableComment = "That would make a good tea sandwich."
2014-12-14 05:01:08 +03:00
case let localScopeValue where localScopeValue.hasSuffix("pepper"):
2019-08-03 14:13:22 +03:00
vegetableComment = "Is it a spicy \(localScopeValue)?"
2014-06-04 11:50:17 +04:00
default: // required (in order to cover all possible input)
2019-08-03 14:13:22 +03:00
vegetableComment = "Everything tastes good in soup."
}
print(vegetableComment)
// You use the `for-in` loop to iterate over a sequence, such as an array, dictionary, range, etc.
for element in shoppingList {
print(element) // shoppingList is of type `[String]` , so element is of type `String`
}
//Iterating through a dictionary does not guarantee any specific order
for (person, job) in immutableOccupations {
print("\(person)'s job is \(job)")
}
for i in 1...5 {
print(i, terminator: " ") // Prints "1 2 3 4 5"
}
for i in 0..< 5 {
print(i, terminator: " ") // Prints "0 1 2 3 4"
}
//for index in range can replace a C-style for loop:
// for (int i = 0; i < 10 ; i + + ) {
// //code
// }
//becomes:
// for i in 0..< 10 {
// //code
// }
//To step by more than one, use the stride(from:to:by:) or stride(from:through:by) functions
//`for i in stride(from: 0, to: 10, by: 2)` is the same as `for (int i = 0; i < 10; i += 2)`
//`for i in stride(from: 0, through: 10, by: 2)` is the same as `for (int i = 0; i < = 10; i += 2)
// while loops are just like most languages
var i = 0
while i < 5 {
i += Bool.random() ? 1 : 0
print(i)
2014-06-04 11:50:17 +04:00
}
2019-08-03 14:13:22 +03:00
// This is like a do-while loop in other languages — the body of the loop executes a minimum of once
repeat {
i -= 1
i += Int.random(in: 0...3)
} while i < 5
2014-06-05 00:22:01 +04:00
2019-08-03 14:13:22 +03:00
// The continue statement continues executing a loop at the next iteration
// The break statement ends a swift or loop immediately
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
// MARK: - Functions
2014-12-14 05:01:08 +03:00
2019-08-03 14:13:22 +03:00
// Functions are a first-class type, meaning they can be nested in functions and can be passed around.
2014-08-24 09:48:54 +04:00
2019-08-03 14:13:22 +03:00
// Function with Swift header docs (format as Swift-modified Markdown syntax)
2014-08-24 09:48:54 +04:00
2019-08-03 14:13:22 +03:00
/// A greet operation.
///
/// - Parameters:
/// - name: A name.
/// - day: A day.
/// - Returns: A string containing the name and day value.
2014-06-04 11:50:17 +04:00
func greet(name: String, day: String) -> String {
2014-08-24 07:48:10 +04:00
return "Hello \(name), today is \(day)."
2014-06-04 11:50:17 +04:00
}
2016-10-08 12:59:20 +03:00
greet(name: "Bob", day: "Tuesday")
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
// Ideally, function names and parameter labels combine to make function calls similar to sentences.
func sayHello(to name: String, onDay day: String) -> String {
return "Hello \(name), the day is \(day)"
}
sayHello(to: "John", onDay: "Sunday")
//Functions that don't return anything can omit the return arrow; they don't need to say that they return Void (although they can).
func helloWorld() {
print("Hello, World!")
}
// Argument labels can be blank
func say(_ message: String) {
print(#"I say "\#(message)""#)
}
say("Hello")
2019-10-22 10:10:07 +03:00
// Default parameters can be omitted when calling the function.
2019-08-03 14:13:22 +03:00
func printParameters(requiredParameter r: Int, optionalParameter o: Int = 10) {
print("The required parameter was \(r) and the optional parameter was \(o)")
}
printParameters(requiredParameter: 3)
printParameters(requiredParameter: 3, optionalParameter: 6)
// Variadic args — only one set per function.
func setup(numbers: Int...) {
// it's an array
let _ = numbers[0]
let _ = numbers.count
}
// pass by ref
func swapTwoInts(a: inout Int, b: inout Int) {
let tempA = a
a = b
b = tempA
}
var someIntA = 7
var someIntB = 3
swapTwoInts(a: & someIntA, b: & someIntB) //must be called with an & before the variable name.
print(someIntB) // 7
type(of: greet) // (String, String) -> String
type(of: helloWorld) // () -> Void
// Passing and returning functions
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
func performFunction(_ function: (String, String) -> String, on string1: String, and string2: String) {
let result = function(string1, string2)
print("The result of calling the function on \(string1) and \(string2) was \(result)")
2014-12-14 05:01:08 +03:00
}
2014-06-04 11:50:17 +04:00
// Function that returns multiple items in a tuple
func getGasPrices() -> (Double, Double, Double) {
2014-08-24 07:48:10 +04:00
return (3.59, 3.69, 3.79)
2014-06-04 11:50:17 +04:00
}
2014-10-04 21:08:23 +04:00
let pricesTuple = getGasPrices()
let price = pricesTuple.2 // 3.79
2014-10-18 06:22:28 +04:00
// Ignore Tuple (or other) values by using _ (underscore)
let (_, price1, _) = pricesTuple // price1 == 3.69
2015-08-04 06:05:22 +03:00
print(price1 == pricesTuple.1) // true
print("Gas price: \(price)")
2014-06-04 11:50:17 +04:00
2015-11-11 02:03:40 +03:00
// Labeled/named tuple params
2015-11-10 02:54:05 +03:00
func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Double) {
return (1.77, 37.70, 7.37)
}
let pricesTuple2 = getGasPrices2()
let price2 = pricesTuple2.lowestPrice
let (_, price3, _) = pricesTuple2
2015-11-10 03:09:48 +03:00
print(pricesTuple2.highestPrice == pricesTuple2.1) // true
print("Highest gas price: \(pricesTuple2.highestPrice)")
2015-11-10 02:54:05 +03:00
2015-11-11 02:03:40 +03:00
// guard statements
func testGuard() {
// guards provide early exits or breaks, placing the error handler code near the conditions.
// it places variables it declares in the same scope as the guard statement.
2019-08-03 14:13:22 +03:00
// They make it easier to avoid the "pyramid of doom"
2015-11-11 02:03:40 +03:00
guard let aNumber = Optional< Int > (7) else {
2019-08-03 14:13:22 +03:00
return // guard statements MUST exit the scope that they are in.
// They generally use `return` or `throw` .
2015-11-11 02:03:40 +03:00
}
2019-10-22 10:10:07 +03:00
2015-11-11 02:03:40 +03:00
print("number is \(aNumber)")
}
testGuard()
2019-08-03 14:13:22 +03:00
// Note that the print function is declared like so:
// func print(_ input: Any..., separator: String = " ", terminator: String = "\n")
// To print without a newline:
print("No newline", terminator: "")
print("!")
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
// MARK: - Closures
2014-06-04 11:50:17 +04:00
2014-07-16 14:20:57 +04:00
var numbers = [1, 2, 6]
2014-06-05 00:22:01 +04:00
// Functions are special case closures ({})
2014-06-04 11:50:17 +04:00
// Closure example.
// `->` separates the arguments and return type
// `in` separates the closure header from the closure body
numbers.map({
2014-08-24 07:48:10 +04:00
(number: Int) -> Int in
let result = 3 * number
return result
})
2014-06-04 11:50:17 +04:00
// When the type is known, like above, we can do this
numbers = numbers.map({ number in 3 * number })
2014-08-24 07:48:10 +04:00
// Or even this
2014-07-16 14:20:57 +04:00
//numbers = numbers.map({ $0 * 3 })
2014-06-04 11:50:17 +04:00
print(numbers) // [3, 6, 18]
2014-08-24 07:48:10 +04:00
// Trailing closure
2016-10-08 12:59:20 +03:00
numbers = numbers.sorted { $0 > $1 }
2014-08-24 07:48:10 +04:00
print(numbers) // [18, 6, 3]
2019-08-03 14:13:22 +03:00
// MARK: - Enums
2014-08-25 03:33:16 +04:00
2019-08-03 14:13:22 +03:00
// Enums can optionally be of a specific type or on their own.
// They can contain methods like classes.
2015-10-08 06:11:24 +03:00
2019-08-03 14:13:22 +03:00
enum Suit {
case spades, hearts, diamonds, clubs
var icon: Character {
switch self {
case .spades:
return "♤"
case .hearts:
return "♡"
case .diamonds:
return "♢"
case .clubs:
return "♧"
}
2014-08-25 03:33:16 +04:00
}
}
2019-08-03 14:13:22 +03:00
// Enum values allow short hand syntax, no need to type the enum type
// when the variable is explicitly declared
var suitValue: Suit = .hearts
2015-11-23 22:12:49 +03:00
2019-08-03 14:13:22 +03:00
// Conforming to the CaseIterable protocol automatically synthesizes the allCases property,
// which contains all the values. It works on enums without associated values or @available attributes.
enum Rank: CaseIterable {
case ace
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
var icon: String {
switch self {
case .ace:
return "A"
case .two:
return "2"
case .three:
return "3"
case .four:
return "4"
case .five:
return "5"
case .six:
return "6"
case .seven:
return "7"
case .eight:
return "8"
case .nine:
return "9"
case .ten:
return "10"
case .jack:
return "J"
case .queen:
return "Q"
case .king:
return "K"
}
}
2015-11-23 22:12:49 +03:00
}
2019-08-03 14:13:22 +03:00
for suit in [Suit.clubs, .diamonds, .hearts, .spades] {
for rank in Rank.allCases {
print("\(rank.icon)\(suit.icon)")
2015-11-23 22:12:49 +03:00
}
2019-08-03 14:13:22 +03:00
}
2015-11-23 22:12:49 +03:00
2019-08-03 14:13:22 +03:00
// String enums can have direct raw value assignments
// or their raw values will be derived from the Enum field
enum BookName: String {
case john
case luke = "Luke"
2015-11-23 22:12:49 +03:00
}
2019-08-03 14:13:22 +03:00
print("Name: \(BookName.john.rawValue)")
2015-11-23 22:12:49 +03:00
2019-08-03 14:13:22 +03:00
// Enum with associated Values
enum Furniture {
// Associate with Int
case desk(height: Int)
// Associate with String and Int
case chair(String, Int)
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
func description() -> String {
//either placement of let is acceptable
switch self {
case .desk(let height):
return "Desk with \(height) cm"
case let .chair(brand, height):
return "Chair of \(brand) with \(height) cm"
}
}
}
2015-11-23 22:12:49 +03:00
2019-08-03 14:13:22 +03:00
var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Chair of Foo with 40 cm"
2015-11-23 22:12:49 +03:00
2019-08-03 14:13:22 +03:00
// MARK: - Structures & Classes
/*
Structures and classes in Swift have many things in common. Both can:
- Define properties to store values
- Define methods to provide functionality
- Define subscripts to provide access to their values using subscript syntax
- Define initializers to set up their initial state
- Be extended to expand their functionality beyond a default implementation
- Conform to protocols to provide standard functionality of a certain kind
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
Classes have additional capabilities that structures don't have:
- Inheritance enables one class to inherit the characteristics of another.
- Type casting enables you to check and interpret the type of a class instance at runtime.
- Deinitializers enable an instance of a class to free up any resources it has assigned.
- Reference counting allows more than one reference to a class instance.
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
Unless you need to use a class for one of these reasons, use a struct.
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
Structures are value types, while classes are reference types.
*/
// MARK: Structures
struct NamesTable {
let names: [String]
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
// Custom subscript
subscript(index: Int) -> String {
return names[index]
2015-11-23 22:12:49 +03:00
}
}
2019-08-03 14:13:22 +03:00
// Structures have an auto-generated (implicit) designated "memberwise" initializer
let namesTable = NamesTable(names: ["Me", "Them"])
let name = namesTable[1]
print("Name is \(name)") // Name is Them
2014-06-05 00:22:01 +04:00
2019-08-03 14:13:22 +03:00
// MARK: Classes
2014-08-25 03:33:16 +04:00
2019-08-03 14:13:22 +03:00
class Shape {
func getArea() -> Int {
2016-01-16 21:30:25 +03:00
return 0
2014-08-24 07:48:10 +04:00
}
}
2019-08-03 14:13:22 +03:00
class Rect: Shape {
2014-08-24 07:48:10 +04:00
var sideLength: Int = 1
2019-10-22 10:10:07 +03:00
2014-08-24 07:48:10 +04:00
// Custom getter and setter property
2019-08-03 14:13:22 +03:00
var perimeter: Int {
2014-08-24 07:48:10 +04:00
get {
return 4 * sideLength
}
set {
2014-08-25 03:33:16 +04:00
// `newValue` is an implicit variable available to setters
2014-08-24 07:48:10 +04:00
sideLength = newValue / 4
}
2014-06-04 11:50:17 +04:00
}
2019-10-22 10:10:07 +03:00
2015-11-10 02:55:53 +03:00
// Computed properties must be declared as `var` , you know, cause' they can change
2015-11-10 02:54:05 +03:00
var smallestSideLength: Int {
return self.sideLength - 1
}
2019-10-22 10:10:07 +03:00
2014-08-25 03:33:16 +04:00
// Lazily load a property
// subShape remains nil (uninitialized) until getter called
lazy var subShape = Rect(sideLength: 4)
2019-10-22 10:10:07 +03:00
2014-08-24 07:48:10 +04:00
// If you don't need a custom getter and setter,
// but still want to run code before and after getting or setting
// a property, you can use `willSet` and `didSet`
var identifier: String = "defaultID" {
2014-08-25 03:33:16 +04:00
// the `willSet` arg will be the variable name for the new value
2014-08-24 07:48:10 +04:00
willSet(someIdentifier) {
print(someIdentifier)
}
2014-06-04 11:50:17 +04:00
}
2019-10-22 10:10:07 +03:00
2014-08-24 07:48:10 +04:00
init(sideLength: Int) {
self.sideLength = sideLength
2014-12-14 05:01:08 +03:00
// always super.init last when init custom properties
2014-10-04 21:08:23 +04:00
super.init()
2014-08-24 07:48:10 +04:00
}
2019-10-22 10:10:07 +03:00
2014-08-24 07:48:10 +04:00
func shrink() {
if sideLength > 0 {
2016-10-01 23:33:04 +03:00
sideLength -= 1
2014-08-24 07:48:10 +04:00
}
2014-06-04 11:50:17 +04:00
}
2019-10-22 10:10:07 +03:00
2014-08-24 07:48:10 +04:00
override func getArea() -> Int {
return sideLength * sideLength
}
}
2014-06-04 11:50:17 +04:00
2014-09-03 03:52:04 +04:00
// A simple class `Square` extends `Rect`
2014-08-24 07:48:10 +04:00
class Square: Rect {
convenience init() {
self.init(sideLength: 5)
}
2014-06-04 11:50:17 +04:00
}
2014-08-24 07:48:10 +04:00
var mySquare = Square()
2014-06-04 11:50:17 +04:00
print(mySquare.getArea()) // 25
mySquare.shrink()
print(mySquare.sideLength) // 4
2014-12-14 05:01:08 +03:00
// cast instance
let aShape = mySquare as Shape
2019-11-02 06:49:53 +03:00
// downcast instance:
// Because downcasting can fail, the result can be an optional (as?) or an implicitly unwrpped optional (as!).
let anOptionalSquare = aShape as? Square // This will return nil if aShape is not a Square
let aSquare = aShape as! Square // This will throw a runtime error if aShape is not a Square
2014-08-24 09:48:54 +04:00
// compare instances, not the same as == which compares objects (equal to)
if mySquare === mySquare {
2015-08-04 06:05:22 +03:00
print("Yep, it's mySquare")
2014-08-24 09:48:54 +04:00
}
2015-02-28 14:28:34 +03:00
// Optional init
class Circle: Shape {
var radius: Int
override func getArea() -> Int {
return 3 * radius * radius
}
2019-10-22 10:10:07 +03:00
2015-02-28 14:28:34 +03:00
// Place a question mark postfix after `init` is an optional init
// which can return nil
init?(radius: Int) {
self.radius = radius
super.init()
2019-10-22 10:10:07 +03:00
2015-02-28 14:28:34 +03:00
if radius < = 0 {
return nil
}
}
}
var myCircle = Circle(radius: 1)
2015-08-04 06:05:22 +03:00
print(myCircle?.getArea()) // Optional(3)
print(myCircle!.getArea()) // 3
2015-02-28 14:28:34 +03:00
var myEmptyCircle = Circle(radius: -1)
2015-08-04 06:05:22 +03:00
print(myEmptyCircle?.getArea()) // "nil"
2015-02-28 14:28:34 +03:00
if let circle = myEmptyCircle {
// will not execute since myEmptyCircle is nil
2015-08-04 06:05:22 +03:00
print("circle is not nil")
2014-08-24 09:48:54 +04:00
}
2019-08-03 14:13:22 +03:00
// MARK: - Protocols
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
// protocols are also known as interfaces in some other languages
2014-06-05 00:22:01 +04:00
2019-08-03 14:13:22 +03:00
// `protocol` s can require that conforming types have specific
// instance properties, instance methods, type methods,
// operators, and subscripts.
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
protocol ShapeGenerator {
var enabled: Bool { get set }
func buildShape() -> Shape
2014-06-04 11:50:17 +04:00
}
2019-08-03 14:13:22 +03:00
// MARK: - Other
2014-12-14 05:01:08 +03:00
2019-08-03 14:13:22 +03:00
// MARK: Typealiases
2014-12-14 05:01:08 +03:00
2019-08-03 14:13:22 +03:00
// Typealiases allow one type (or composition of types) to be referred to by another name
typealias Integer = Int
let myInteger: Integer = 0
2015-10-08 06:11:24 +03:00
2019-08-03 14:13:22 +03:00
// MARK: = Operator
2015-02-28 14:28:34 +03:00
2019-08-03 14:13:22 +03:00
// Assignment does not return a value. This means it can't be used in conditional statements,
// and the following statement is also illegal
// let multipleAssignment = theQuestion = "No questions asked"
//But you can do this:
let multipleAssignment = "No questions asked", secondConstant = "No answers given"
2014-12-14 05:01:08 +03:00
2019-08-03 14:13:22 +03:00
// MARK: Ranges
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
// The ..< and . . . operators create ranges .
2014-06-04 11:50:17 +04:00
2019-08-03 14:13:22 +03:00
// ... is inclusive on both ends (a "closed range") — mathematically, [0, 10]
let _0to10 = 0...10
2019-08-03 17:38:55 +03:00
// ..< is inclusive on the left , exclusive on the right ( a " range " ) — mathematically , [ 0 , 10 )
2019-08-03 14:13:22 +03:00
let singleDigitNumbers = 0..< 10
// You can omit one end (a "PartialRangeFrom") — mathematically, [0, ∞)
let toInfinityAndBeyond = 0...
// Or the other end (a "PartialRangeTo") — mathematically, (-∞, 0)
let negativeInfinityToZero = ..< 0
// (a "PartialRangeThrough") — mathematically, (-∞, 0]
let negativeInfinityThroughZero = ...0
2014-08-25 03:33:16 +04:00
2019-08-03 14:13:22 +03:00
// MARK: Wildcard operator
// In Swift, _ (underscore) is the wildcard operator, which allows values to be ignored
// It allows functions to be declared without argument labels:
func function(_ labelLessParameter: Int, label labeledParameter: Int, labelAndParameterName: Int) {
print(labelLessParameter, labeledParameter, labelAndParameterName)
2014-08-24 07:48:10 +04:00
}
2019-08-03 14:13:22 +03:00
function(0, label: 0, labelAndParameterName: 0)
2014-08-24 07:48:10 +04:00
2019-08-03 14:13:22 +03:00
// You can ignore the return values of functions
func printAndReturn(_ str: String) -> String {
print(str)
return str
2014-08-25 03:33:16 +04:00
}
2019-08-03 14:13:22 +03:00
let _ = printAndReturn("Some String")
2014-08-25 03:33:16 +04:00
2019-08-03 14:13:22 +03:00
// You can ignore part of a tuple and keep part of it
func returnsTuple() -> (Int, Int) {
return (1, 2)
}
let (_, two) = returnsTuple()
2015-10-08 06:11:24 +03:00
2019-08-03 14:13:22 +03:00
// You can ignore closure parameters
let closure: (Int, Int) -> String = { someInt, _ in
return "\(someInt)"
}
closure(1, 2) // returns 1
2015-01-21 01:52:31 +03:00
2019-08-03 14:13:22 +03:00
// You can ignore the value in a for loop
for _ in 0..< 10 {
// Code to execute 10 times
2014-08-25 03:33:16 +04:00
}
2014-10-04 21:08:23 +04:00
2019-08-03 14:13:22 +03:00
// MARK: Access Control
2014-08-25 03:33:16 +04:00
2019-08-03 14:13:22 +03:00
/*
Swift has five levels of access control:
- Open: Accessible *and subclassible* in any module that imports it.
- Public: Accessible in any module that imports it, subclassible in the module it is declared in.
- Internal: Accessible and subclassible in the module it is declared in.
- Fileprivate: Accessible and subclassible in the file it is declared in.
2019-08-03 17:38:55 +03:00
- Private: Accessible and subclassible in the enclosing declaration (think inner classes/structs/enums)
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
See more here: https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html
*/
2020-10-17 22:19:26 +03:00
// MARK: Preventing Overrides
// You can add keyword `final` before a class or instance method, or a property to prevent it from being overridden
class Shape {
final var finalInteger = 10
}
// Prevent a class from being subclassed
final class ViewManager {
}
2019-08-03 14:13:22 +03:00
// MARK: Conditional Compilation, Compile-Time Diagnostics, & Availability Conditions
// Conditional Compilation
#if false
print("This code will not be compiled")
#else
print("This code will be compiled")
#endif
/*
Options are:
os() macOS, iOS, watchOS, tvOS, Linux
arch() i386, x86_64, arm, arm64
swift() >= or < followed by a version number
compiler() >= or < followed by a version number
canImport() A module name
targetEnvironment() simulator
*/
#if swift(<3)
println()
#endif
// Compile-Time Diagnostics
// You can use #warning (message) and #error (message) to have the compiler emit warnings and/or errors
#warning("This will be a compile-time warning")
// #error ("This would be a compile-time error")
2014-08-25 03:33:16 +04:00
2019-08-03 14:13:22 +03:00
//Availability Conditions
if #available (iOSMac 10.15, *) {
// macOS 10.15 is available, you can use it here
} else {
// macOS 10.15 is not available, use alternate APIs
}
// MARK: Any and AnyObject
// Swift has support for storing a value of any type.
// For that purpose there are two keywords: `Any` and `AnyObject`
// `AnyObject` == `id` from Objective-C
// `Any` works with any values (class, Int, struct, etc.)
var anyVar: Any = 7
anyVar = "Changed value to a string, not good practice, but possible."
let anyObjectVar: AnyObject = Int(1) as NSNumber
// MARK: Extensions
// Extensions allow you to add extra functionality to an already-declared type, even one that you don't have the source code for.
2014-08-25 03:33:16 +04:00
2015-11-23 22:12:49 +03:00
// Square now "conforms" to the `CustomStringConvertible` protocol
2015-11-10 03:09:48 +03:00
extension Square: CustomStringConvertible {
2014-08-24 07:48:10 +04:00
var description: String {
return "Area: \(self.getArea()) - ID: \(self.identifier)"
}
}
2015-08-04 06:05:22 +03:00
print("Square: \(mySquare)")
2014-08-24 07:48:10 +04:00
2014-08-24 09:48:54 +04:00
// You can also extend built-in types
extension Int {
2019-08-03 14:13:22 +03:00
var doubled: Int {
return self * 2
2014-08-24 09:48:54 +04:00
}
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
func multipliedBy(num: Int) -> Int {
2014-08-24 09:48:54 +04:00
return num * self
}
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
mutating func multiplyBy(num: Int) {
self *= num
}
2014-08-24 09:48:54 +04:00
}
2019-08-03 14:13:22 +03:00
print(7.doubled) // 14
print(7.doubled.multipliedBy(num: 3)) // 42
// MARK: Generics
2014-08-24 09:48:54 +04:00
2014-10-04 21:08:23 +04:00
// Generics: Similar to Java and C#. Use the `where` keyword to specify the
2014-06-05 00:22:01 +04:00
// requirements of the generics.
2014-06-04 11:50:17 +04:00
2016-10-08 12:59:20 +03:00
func findIndex< T: Equatable > (array: [T], valueToFind: T) -> Int? {
for (index, value) in array.enumerated() {
2014-08-24 07:48:10 +04:00
if value == valueToFind {
return index
}
}
return nil
}
2019-12-03 00:57:13 +03:00
findIndex(array: [1, 2, 3, 4], valueToFind: 3) // Optional(2)
2019-08-03 14:13:22 +03:00
// You can extend types with generics as well
extension Array where Array.Element == Int {
var sum: Int {
var total = 0
for el in self {
total += el
}
return total
}
}
// MARK: Operators
2014-08-24 09:48:54 +04:00
// Custom operators can start with the characters:
// / = - + * % < > ! & | ^ . ~
// or
// Unicode math, symbol, arrow, dingbat, and line/box drawing characters.
2016-10-08 12:59:20 +03:00
prefix operator !!!
2014-08-24 09:48:54 +04:00
2014-08-25 03:33:16 +04:00
// A prefix operator that triples the side length when used
2016-10-08 12:59:20 +03:00
prefix func !!! (shape: inout Square) -> Square {
2014-08-24 09:48:54 +04:00
shape.sideLength *= 3
return shape
}
2014-08-25 03:33:16 +04:00
// current value
2015-08-04 06:05:22 +03:00
print(mySquare.sideLength) // 4
2014-08-25 03:33:16 +04:00
// change side length using custom !!! operator, increases size by 3
!!!mySquare
2015-08-04 06:05:22 +03:00
print(mySquare.sideLength) // 12
2015-10-08 10:00:13 +03:00
// Operators can also be generics
2016-10-08 12:59:20 +03:00
infix operator < - >
func < - > < T: Equatable > (a: inout T, b: inout T) {
2015-10-08 10:00:13 +03:00
let c = a
a = b
b = c
}
var foo: Float = 10
var bar: Float = 20
foo < - > bar
print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0"
2019-08-03 14:13:22 +03:00
// MARK: - Error Handling
// The `Error` protocol is used when throwing errors to catch
enum MyError: Error {
case badValue(msg: String)
case reallyBadValue(msg: String)
}
// functions marked with `throws` must be called using `try`
func fakeFetch(value: Int) throws -> String {
guard 7 == value else {
throw MyError.reallyBadValue(msg: "Some really bad value")
}
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
return "test"
}
func testTryStuff() {
// assumes there will be no error thrown, otherwise a runtime exception is raised
let _ = try! fakeFetch(value: 7)
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
// if an error is thrown, then it proceeds, but if the value is nil
// it also wraps every return value in an optional, even if its already optional
let _ = try? fakeFetch(value: 7)
2019-10-22 10:10:07 +03:00
2019-08-03 14:13:22 +03:00
do {
// normal try operation that provides error handling via `catch` block
try fakeFetch(value: 1)
} catch MyError.badValue(let msg) {
print("Error message: \(msg)")
} catch {
// must be exhaustive
}
}
testTryStuff()
2014-07-16 14:20:57 +04:00
```