Swift Syntax Flashcards
for-in loop
for in { // code to be executed }
if statement
var Christmas = true if Christmas { print("A Savior has been born!") }
function
func (: , : , ... ) -> { // Function code }
calling a function with specified parameter/data type
funcName(paramName:paramArgument)
while loop
while condition { // Execute while condition remains true }
example while total < 50 { let diceRoll = Int.random(in: 1...6) total += diceRoll }
for-in loops
used to iterate over collection items like ranges and strings.
stride( )
creates a range that we can customize.
Create an empty dictionary using dictionary literal syntax
var dictionaryName: [KeyType: ValueType] = [:]
create a populated dictionary
var dictionaryName: [KeyType: ValueType] = [ Key1: Value1, Key2: Value2, Key3: Value3 ]
create a dictionary with type inference
var fruitStand = [
“Apples”: 12,
“Bananas”: 20
]
add new key-value to dictionary (or update existing)
dictionaryName[NewKey] = NewValue
update dictionary value using updateValue() method
dictionaryName.updateValue(“NewValueName”, forKey: “KeyName”)
remove key-value pair from dictionary using nil
dictionaryName[“keyName”] = nil
remove key-value pair from dictionary using .removeValue( ) method
dictionaryName.removeValue(forKey:”keyName”)
remove all elements from a dictionary
dictionaryName.removeAll( )
determine if a dictionary is empty
dictionaryName.isEmpty
determine the number of elements contained in a dictionary
dictionaryName.count
extract a value from dictionary and assign it to a new variable
var newVariable = dictionaryName[“keyName”]
if-let statement
if let newVarName = dictionaryName["keyName"] { action to perform }
iterate through a dictionary
for (keyHolder, valueHolder) in dictionaryName { // Body of loop }
The syntax for creating an instance
var ferris = Student()
Syntax for init() method
class className { var property = value init (property: valueType) { self.property = property } }
Syntax to create a subclass that inherits from a superclass
class Subclass: Superclass { }
Create subclass to inherit from super class with new property with default value of 2.0
class SubClass: SuperClass { var newProperty = 2.0 }
closed range operator
x…y // Starts at x and ends at y
half-open range operator
x..
One-sided range operator
x… /* or */ …y // specifies a range that can extend as far as possible in a specified range direction until the natural beginning or end of the range is reached, can be used w/strings.
The Ternary Operator
condition ? true expression : false expression
Nil Coalescing Operator
let customerName: String? = nil print("Welcome back, \(customerName ?? "customer")") //The above example will output text which reads "Welcome back, customer" because the customerName optional is set to nil.
repeat … while loop
repeat { // Swift statements here } while EX. var i = 10 repeat { i -= 1 } while (i > 0) //In the repeat .. while example above the loop will continue until the value of a variable named i equals 0
“break” statement
var j = 10 for _ in 0 ..<100 { j += j if j > 100 { break } print ("j = \ (j) ") }
“continue” statement
var i = 1 while i < 20 { i += 1 if ( i % 2 ) != 0 { continue } print ( " i = \ ( i ) " ) } // The "continue" statement in the above example will cause the print call to be skipped unless the value of "i" is even. // I.E. The print call will be skipped unless the condition is met
if … else if …
if let x = 9 if x == 10 { print ( " x is 10 " ) } else if x == 9 { print ( " x is 9 " ) } else if x == 8 { print ( " x is 8 " ) }
guard statement
guard ese { // code to be executed if expression is false
} // code here is executed if expression is true
switch statement
switch expression { case match1: statements case match2: statements case match3, match4: statements default: statements }
Function with default function parameter
func buildMessageFor(_ name: String = "Customer, count: Int ) -> String } return ( "\(name), you are customer number \ (count) " ) }
Function that returns multiple result values
func sizeConverter (_ length: Float ) -> (yards: Float, centimeters: Float, meters: Float) { let yards = length * 0.0277778 let centimeters = length * 2.54 let meters = length * 0.0254
return (yards, centimeters, meters)
}
closure expression
The following code declares a closure expression and assigns it to a constant named sayHello and then calls the function via the constant reference EX: let sayHello = { print( "Hello" ) } sayHello( )
closure expression configured to accept parameters and return results
{ ( : , , ... ) -> < return type> in // Closure expression code here }
An array may be initialized with a collection of values (referred to as an array literal) at creation time using the following syntax
var variableName: [type] = [value 1, value2, value3, ……….]
The following syntax can be used to create an empty array
var variableName = [type] ( )
Array initialized to a specific size with each array element pre-set with a specified default value
var nameArray = [String] (repeating: “My String”, count: 10)
Syntax to create a new array by adding together two existing arrays
let thirdArray = firstArray + secondArray
forEach( ) array method
arrName.forEach { element in print(element) }
A new dictionary may be initialized with a collection of values (referred to as a dictionary literal) at creation time using the following syntax
var variableName: [key type: value type] = [key 1: value 1, key 2, value2 …. ]
Syntax to create an empty dictionary
var variableName = key type: value type
The following code creates an empty dictionary designated to store integer keys and string values
var myDictionary = [Int: String] ( )
The following code iterates through all the entries in a dictionary, outputting both the key and value for each entry
for (keyName, valueName) in arrayName {
print (“Key Name: (keyName), valueName: (valueName)”)
}