BASICS OF Swift PROGRAMMING LANGUAGE
Swift SYNTAX
Swift CONSTANTS & VARIABLES
Swift TYPE INFERENCE
let constant = 1 // readonly, cannot be-assignedconstant = 2 // ✘ ERROR!!!var variable = 1 // readwrite, can be re-assigned
variable = 2 // OK
// Type inference multiple variables var variable1 = 1,variable 2 = 2, variable = 3
By convention you should prefer to use 'let' over 'var', when possible.
Swift TYPE ANNOTATIONS
let constant = 1let constant: Int = 1 // no need for : Intvar variable: Int
variable = 1
// Type annotations multiple variablesvar double1, double2, double3: Double
Swift NUMBERS
Swift INT, UINT, FlOAT & DOUBLE
var magic: Int = 42 // decimal0b101010 // binary
0o52 // octal
0x2A // hexadecimallet pi: Double = 3.14 // 64-bit (default)let pi: Float = 3.14 // 32-bit
000009.90 // padded
1_000_000.000_000_1 // underscores
Swift BOOLEAN
Swift TRUE & FALSE
let enabled: Bool = true // obj-c YESlet hidden = false // obj-c NO
Swift TYPE ALIASES
Swift DEFINE AN ALTERNATIVE NAME FOR AN EXISTING TYPES
typealias SmallIntAlias = UInt16let min = SmallIntAlias.min // exactly like original UInt16.min
Swift TUPLES
Swift LIGHTWEIGHT, TEMPORARY CONTAINERS FOR MULTIPLE VALUES
let complex = (1.0, -2.0) // Compound Type: (Double, Double)
let (real, imag) = complex // Decompose
let (real, _) = complex // Underscores
// Access by index
let real = complex.0
let imag = complex.1
// Name elements
let complex = (real: 1.0, imag: -2.0)
let real = complex.real
Swift OPTIONALS
Swift AN OPTIONAL VALUE EITHER CONTAINS A VALUE OR NIL
var optionalInt: Int? = 42optionalInt = nil // to indicate that the value is missing
var optionalDouble: Double? // automatically sets to nil
// Check if nil
optionalDouble == nil
optionalDouble != nil
Swift FORCE UNWRAP & OPTIONAL BINDING
// Force unwarplet optionalInt: Int? = 42let definietlyInt = optionalInt! // throws runtime error if nil//Optional bindingif let definitelyInt = optionalInt {
// runs if optionalInt is not nil and sets definitelyInt: Int
}
Swift IMPLICITLY UNWRAPPED OPTIONALS
// Used mainly for class initializationvar assumedInt: Int! // set to nil
assumedInt = 42
var implicitInt: Int = assumedInt // do not need an exclamation mar
implicitInt = assumedInt // ✘ RUNTIME ERROR !!!
Swift OPERATORW
Swift COMMON OPERATORS 1/2
// Modulo Operator3 & 2 // 1
// Increment and Decrement Operator
i++; ++i; i--; --i
// Compound Assignment Operator
i += 1 // i = 1 + 1
// Logical Operator
a || b && c // equivalent to a || (b && c)
SwIft COMMON OPERATORS 2/2
// Ternary Conditional Operator(a == b ? 1 /* if true */ : 0 /* if false*/)
// Nil Coalescing Operator
a ?? b // a != nil ? a! : b
// Closed Range Operator
0...2 // 0, 1, 2
// Half Open Range Operator
0..<2 // 0, 1
Swift LOOPS
Swift FOR [IN]
// old school c-style for loopfor var index = 0; index <2; index++ { /* use index */ }// new iterator-style for -in loopfor value in 0..<2 { /* use value */ }
Swift [DO] WHILE
// while evaluates its expression at the top of the loopwhile x > 2 { /* */ }// do-while evaluates its expression at the bottom of the loopdo { /* executed at least once */ } while x > 2
Swift CONDITIONALS
Swift IF-ELSE
let temperature = 40var feverish: Boolif temperature > 37 {feverish = true
} else {
feverish = false
}
Swift SWITCH
switch x { // breaks by defaultcase value 1 :/* ... */case value2, value 3:
fallthrough // to not breakdefault:
/* ... */
} // switch must be exchaustive
Swift SWITCH RANGE MATCHING
switch count {case 0:
/* ... */case 1...9:
/* ....*/default:
/* ... */
}
Swift SWITCH TUPLE MATCHING
switch point {case (0, 0):/* ... */case (_, 0);
/* ... */case (let x, 1): // value binding
/* use x value */default:
/* ... */
}
Swift SWITCH WHERE
switch point {case let (x, y) where x == y:
/* use x value */case let (x, y):
/* use x abd y values */
} // switch is exhaustive without default
Swift FUNCTIONS & CLOSURES
Swift DECLARATION & CALL
// With parameters and return valuefunc foo(parameter1: Type1, parameter1: Type 2) -> ReturnType { /* function body */ }foo(argument1, argument2) // call
// Without parameters and return valuefunc bar() -> Void { /* function body */ }func baz() -> () { /* function body */ }func quz() { /* function body */ }
quz() // call
Swift EXTERNAL, LOCAL & DEFAULT PARAMETERS
// external and local parameter namesfunc foo(externalParameterName localParameterName: Type) { /* body use localParameterName */ }foo(externalParameterName: argument) // call must use externalParameterName label
// # = shorthand for external parameter namesfunc bar (#parameterName: Type) { /* body use parameterName */ }
bar (parameterName: argument) // call must use parameterName label
// default parameter valuesfunc baz(parameter1: Type1, parameterWithDefault: Int = 42) { /* ... */ }
baz(argument1) // call can omit value for parameterWithDefault
// automatic external parameter name for default parameters, as if declared #parameterWithDefault
baz(argument1, parameterWithDefault: 10)
Swift VARIADIC PAMETERS
func foo(parameter: Int...) {
/* parameter */ // use parameter as an array with type [Int]
}
foo(1, 2, 3, 4, 5) // call with multiple argument
Swift VARIABLE PARAMETERS
// let creates a local imutable copy of parameter - let is the default and can be omitted
// var creates a local mutable copy of parameter - var can't modify given instance passed as value
func foo(let constantParameter: Int, var variableParameter: Int ) {
constantParameter += 1 // ✘ ERROR !!
variableParameter += 2 // OK
}
// inout allows to modify given instance passed as value
func bar(inout parameter: Int) { parameter = 42 }
var x = 0 // cannot be declared with 'let'
bar (&x) // need the & in the call
x // = 42
Swift FUNCTION TYPE
// The Type of addOne function is (Int) -> Intfunc addOne(n: Int) -> Int { return n + 1 }
// Function as parameterfunc foo(functionParameter: (Int) { /* */ }
foo(addOne)
// Function as return typefunc bar() -> (Int) -> Int {
func addTwo(n: Int) -> Int { return n + 2 }
return AddTwo
}
Swift CURRIED FUNCTIONS
// Rewrite a function that takes multiple parameters as
// an equivalent function that takes a single parameter and returns a function
func AddTwoInts(a: Int, b: Int) -> Int { return a + b }
func AddTwoIntsCurried (a: Int) -> (Int) -> Int {
func AddTheOtherInt(b: Int) -> Int { return a + b }
return AddTheOtherInt
}
// equivalent to:
func addTwoIntsCurried (a: Int)(b: Int) -> Int { return a + b }
addTwoInts(1, 2) // = 3
addTwoIntsCurried(1)(2) // = 3
Swift MEANING SYNTAX
Closures are blocks of functionality that can be passed around{ (parameter1: Type1, parameter2: Type2) -> ReturnType in / * ... */
}
Swift SORTING WITHOUT CLASSES
func sorted(array: [Int], algorithm: (Int, Int) -> Bool) -> [Int] { /* ... */ }let array = [1, 2, 3]
func backwards(i1: Int, i2: Int) { return i1 > i2}
var reversed = sorted(array, backwards)
Swift SORTING WITH CLOSURES
// Fully declared closurereversed = sorted(array, { (i1: Int, i2: (Int) -> Bool in return i1 > i2 } )
// Infer closure type
reversed = sorted(array, { (i1, i2) in return i1 > i2 } )
// Implicit returns
reversed = sortex(array, { (i1, i2) in i1 > i2 } )
Swift SORTING WITH CLOSURES 2/2
// Shorthand argument namesreversed = sortex(array, { $0 > $1 } )
// Operator functions
reversed = sortex(array, >)
// trailing closure: outside of () only if it's function's final argument
// optional parentheses
array.map({ $0 + 1 })
array.map { $0 + 1 } // equivalent
Swift CAPTURING VALUES
Closures can capture and store references to any contstants and variables from the context in which they are defined.func makeRepeaterWithRepeatedValue(valueToRepeat: Int) -> () -> [Int] {
var captureArray = []
func repeater() -> [Int] {
capturedArray.append(valueToRepeat)
return capturedArray
}
return repeater
}
let repeater3 = makeRepeaterWithRepeatedValue()
repeater3() // [3]
repeater3() // [3, 3]
Swift ADVANCED OPERATORS
// Prefix Operator Functions
prefix func -(vector: Vector) -> Vector { /* return the opposide Vector */ }
let negativeVector = -positiveVector
// Infix Operator Functionsfunc +(left: Vector, right: Vector) -> Vector { /* return the Vector sum */ }func +=(inout left: Vector, right: Vector) { /* set left to the Vector sum */ }var originalVector = /* a Vector */; var anotherVector = /* another Vector */;
originalVector += anotherVector
// Custom operatorsprefix operator +++ {} // Custom Infix Operators can specify Precedence and Associativityprefix func +++(inout vector: Vector) -> Vector { vector += vector; return vector; }
Swift DATA TYPES & INSTANCES
Swift ENUMERATIONS
Swift AN ENUMERATION DEFINES A COMMON TYPE FOR A GROUP OF ITEMS
enum CellState {case Alive
case Dead
case Error
}let state1 = CellState.Alivelet state2 : CellState = .Dead // if known type, can drop enumeration nameswitch state1 {
case .Alive:
case .Dead:
default:
}
Swift AN ENUMERATION ITEM CAN HAVE AN ASSOCIATED VALUE
enum CellState {case Alive
case Dead
case Error(Int) // associated value can also be a tuple of values
}let errorState = CellState.Error(-1);switch errorState {
case .Alive:
case .Dead:
case .Error(let errorCode): // == case let .Error(errorCode)):
/ * use errorCode */
}
Swift AN ENUMERATION ITEM CAN HAVE A RAW VALUE
enum CellState {case Alive = 1 case Dead = 2
case Error = 3
}enum CellState: Int { // Specify the Item Raw Value Type
case Alive = 1, Dead, Error // Int auto-increment }let stateValue = CellState.Error.rawValue // 3 let aliveState: CellState? = CellState(rawValue: 1) // CellState.Alive
Swift Structures
Swift COPY VALUE ON ASSIGNMENT OR WHEN PASSED INTO FUNCTION
// Structures are value typesstruct CellPoint {
var x = 0.0
var y = 0.0
}
// Structures are always copied when they are passed around
var a = CellPoint(x: 1.0, y: 2.0); var b = a; b.x = 3.0; a.x // 1.0 - a not changed
Swift Strings & Characters 1/2
// String Declaration
var emptyString = "" // == var emptyString = String()
emptyString.isEmpty // true
let constString = "Hello"
// Character Declaration
var character: Character = "p"
for character in "Hello" { // "H", "e", "l", "l", "o" }
// Declare a String as var in order to modify it
var growString = "a"; growString += "b"; growString.append("c")
countElements(growString) // 3
Swift Strings & Characters 2/2
// String Interpolation
let multiplier = 2
let message = "(multiplier) times 2.5 is (Double(multiplier) * 2.5)"
// Print a message in the std output
println(message)
// Comparing Strings
let str1 = "Hello"; let str2 = "Hello";
str1 == str2 // true
str1.hasPrefix("Hel") // true
str2.hasSuffix("llo") // true
Swift Arrays
// Array Declaration
var emptyArray = [Int]() // Array()
var emptyArray : [Int] = []
var array = [Int](count: 2, repeatedValue: 0)
var array = [25, 20, 16]
// Array Access: subscript out of bounds generate crash
array[1] // 20
array[1000] // ❌ RUNTIME ERROR !!!
array.count // 3
array.isEmpty // false
// Array Iteration
for value in array { /* use value / } for (index, value) in enumerate(array) { / use index and value */ }
Swift VARIABLE ARRAYS
var variableArray = ["A"]variableArray = ["X"] // ["X"]
variableArray[0] = "A" // ["A"]
variableArray.append("B"); // ["A", "B"]
variableArray += ["C", "D"] // ["A", "B", "C", "D"]
variableArray.insert("Z", atIndex: 4) // ["A", "B", "C", "D", "Z"]
let a = variableArray.removeAtIndex(1) // ["A", "C", "D", "Z"]
variableArray[1…2] = ["M"] // ["A", "M", "Z"]
let l = variableArray.removeLast() // ["A", "M"]
Swift CONSTANT ARRAYS
let constantArray = ["A"]
constantArray = ["X"] // ❌ ERROR !!!
constantArray[0] = "Y" // ❌ ERROR !!!
constantArray.append("B"); // ❌ ERROR !!!
constantArray.removeAtIndex(0) // ❌ ERROR !!!
Swift Dictionaries
// Dictionary Declarationvar emptyDictionary = [String, Int]() // Dictionary()
var emptyDictionary : [String, Int] = [:] // key : value
var dictionary = ["First" : 25, "Second" : 20, "Third" : 16]
// Dictionary Access: subscript return Optional
let second: Int? = dictionary["Second"] // .Some(20)
let last: Int? = dictionary["Last"] // nil
dictionary.count // 3
dictionary.isEmpty // false
// Dictionary Iteration
for (key, value) in dictionary { /* use key and value */ }
dictionary.keys // [String]
dictionary.values // [Int]
Swift VARIABLE DICTIONARIES
var variableDictionary = ["First" : 25]variableDictionary = ["Second" : 20] // ["Second" : 20]
variableDictionary["Third"] = 16 // ["Second" : 20, "Third" : 16]
let oldKeyValue = variableDictionary.updateValue(18, forKey: "Second")
// oldValue => 20 // ["Second" : 18, "Third" : 16]
// removes key
variableDictionary["Second"] = nil // ["Third" : 16]
let removedValue = variableDictionary.removeValueForKey("Third")
// removedValue => 25 // [:]
Swift CONSTANT DICTIONARIES
let constantDictionary = ["First" : 25, "Second" : 20, "Third" : 16]constantDictionary = ["Last" : 0] // ❌ ERROR !!!
constantDictionary["Third"] = 15 // ❌ ERROR !!!
constantDictionary["Forth"] = 21 // ❌ ERROR !!!
constantDictionary["First"] = nil // ❌ ERROR !!
Swift CLASSES
Swift COPY REFERENCE ON ASSIGNMENT OR WHEN PASSED INTO FUNCTION
// Classes are reference typesclass Person {
var name: String?
var age: Int = 0
}
// Class reference (not object) are copied when they are passed around
var giuseppe = Person() let joseph = giuseppe
joseph.name = "Joseph"
giuseppe.name // "Joseph"
// Compare references using === and !==
giuseppe === joseph // true
Swift PROPERTIES
Swift STORED INSTANCE PROPERTIES
class Cell {let name: String // constant stored property
var position: CellPoint? // variable stored property
var score: Int = 10 // variable stored property with default value
lazy var spa = Spa() // lazy stored property (only var)
// lazy: a property whose initial value is not calculated until the first time it is used
}struct CellPoint {
var x = 0.0 // variable stored property with default value
var y = 0.0 // variable stored property with default value
}
// Enumerations do not have instance stored properties
SWift COMPUTED INSTANCE PROPERTIES 1/2
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
// Also available for Enumerations and Classes
Swift COMPUTED INSTANCE PROPERTIES 2/2
struct Rect {var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set { // shorthand 'newValue' equivalent
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
// readonly can omit 'get' keyword
var area: Double { return size.width * size.height }
}
KEEP LEARNING Swift!
https://swift.org/documentation/ - Swift Official documentationhttps://stackoverflow.com/questions/tagged/swift - Swift on stackoverflow
No comments:
Post a Comment