Swift 4 - Useful Information - Control Flow & Collections

Conditional Statements

The if Statement


The most basic if statement contains a single if condition, and executes a set of statements only if that condition is true:
var temp = 25
if temp <= 30 {
print("It's cold.")
}
You can specify additional conditions by chaining together multiple if statements.
if cardValue == 11 {
print("Jack")
} else if cardValue == 12 {
print("Queen")
} else {
print("Not found")
}
The switch Statement
Each case begins with the keyword case:
switch distance {
case 0:
print("not a valid distance")
case 1,2,3,4,5:
print("near")
default:
print("too far")
}
Swift doesn't require break statements, but will still accept one to match and ignore a particular case, or to break out of a matched case before that case has completed its execution.

Where

The where clause checks for additional conditions.
let myPoint = (1, -1)
switch myPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
The final case matches all possible remaining values; a default case is not necessary to have an exhaustive switch statement.

The while Loop
while loop performs a set of statements until a condition becomes false.
while a < b {
print(a)
a+=1
}

The code will execute until the a+=1 statement renders a < b as false.

Repeat-While

The repeat-while loop is the alternate while loop. It first makes a single pass through the loop block, then considers the loop's condition, and repeats the loop until the condition shows as false.
repeat {
x -= 1
} while x > 0
Swift's repeat-while loop is similar to a do-while loop in other languages.

The for-in Loop
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25




The index variable is set at the first value in the range (1). The statements within the for loop are then executed in sequence, through the final item in the range (5).

Control Transfer
Control transfer statements alter the code execution by transferring control from one piece of code to another. Swift's four control transfer statements are continuebreakfallthrough, and return.

A for loop with a condition and an incrementer still evaluates the incrementer after the continue statement is initiated. The loop itself continues to work as usual; only the code within the loop's body is skipped.

Fallthrough

In Swift, switch statements do not fall through the bottom of each case into the next. Instead, the entire switch statement completes its execution when the first matching case is completed. 
By contrast, C requires insertion of an explicit break statement at the end of every switch case to prevent fallthrough. By eliminating default fallthrough, Swift allows for more concise and predictable switch statements in comparison with C, and thus avoids inadvertently executing multiple switch cases.

In cases that require C-style fallthrough behavior, use the fallthrough keyword on a case-by-case basis. The example below uses fallthrough to create a number's textual description.
let myInt = 5
var desc = "The number \(myInt) is"
switch myInt {
case 2, 3, 5, 7, 11, 13, 17, 19:
desc += " a prime number, and also"
fallthrough
default:
desc += " an integer."
}
print(desc)
This prints "The number 5 is a prime number, and also an integer."

If myInt's value is one of the prime numbers in the list, text noting that the number is prime is appended to the end of the description. The fallthrough keyword then causes it to "fall into" the default case.
The fallthrough keyword does not check case conditions in the switch case into which execution falls. As with C’s standard switch statement behavior, the fallthrough keyword moves code execution directly to the statements inside the next (or default) case block.


String Interpolation

String interpolation includes the values of a mix of constants, variables, literals, and expressions inside a string literal to form a new String value. Prefix each item with a backslash, place the item in parentheses, and insert it into the string literal.
let mult = 4
let message = "\(mult) times 1.5 is \(Double(mult) * 1.5)"
// message is "4 times 1.5 is 6"
In the above example, the multiplier value is inserted into the string literal as \(mult). When the string interpolation is evaluated prior to creating the actual string, this placeholder is replaced with the actual value of mult.

Later in the string, the value of mult appears within a larger expression within the string literal: \(Double(mult) * 1.5). The expression calculates the value of Double(mult) * 1.5 and then inserts the result (6) into the string. 
The expressions appearing inside of parentheses within an interpolated string cannot contain an unescaped double quote ("), backslash (\), carriage return, or line feed.


Counting Characters

To retrieve a count of the Character values in a string, use the count property of the string:
let someString = "I am learning with SoloLearn"
print("someString has \(someString.count) characters")
// prints "someString has 28 characters"
When using the characters property, the character count does not always match the length property of an NSString containing the same characters. The length of an NSString is based on the number of 16-bit code units within the string's UTF-16 representation, as opposed to the number of Unicode extended grapheme clusters within the string.

Comparing Strings

Swift offers three options for comparing textual values: string and character equality, prefix equality, and suffix equality.
Use the "equal to" operator (==) and the "not equal to" operator (!=) to determine string and character equality.
let s1 = "We are alike"
let s2 = "We are alike"
if s1 == s2 {
print("These two strings are equal")
}
// prints "These two strings are equal"
Use the string's hasPrefix and hasSuffix methods to determine whether a string has a particular string prefix or suffix. Both methods take a single argument of type String and return a Boolean value.

Arrays



An array is an ordered list of values of the same type, in which the same value can appear multiple times at different positions. In Swift, the array type can be written in full as Array<T>, in which T represents which value type the array is allowed to store. The array type can also be expressed in shorthand form, as [T].
Although the two forms are identical in function, the shorthand will appear throughout this tutorial in reference to an array type.

Creating an Empty Array



Create an empty array of a certain type using initializer syntax.
var someInts = [Int]()
Note that the type of the someInts variable is inferred to be [Int],  from the type of the initializer.
var array = ([ ])

Array with a Default Value

Swift's Array type also provides an initializer for creating an array of a certain size with all of its values set to the same default value. You pass this initializer the number of items to be added to the new array (called count) and a default value of the appropriate type (called repeating):
var fourDoubles = [Double](repeating: 0.0, count: 4)
fourDoubles is of type [Double], and equals [0.0, 0.0, 0.0, 0.0].

Array Literal



Using an array literal is another way to initialize an array. The array literal is shorthand for one or more values written as an array collection, and is written as a list of values, separated by commas, with square brackets at beginning and end.[value 1, value 2, value 3]
The example below creates an array called shoppingList, for storing String values:
var shoppingList: [String] = ["Bread", "Milk"]
This particular array can store only String values, as it has String specified as its value type.

Because of Swift's type inference, you don't have to write out the array type. Be sure to initialize with an array literal containing values of that same type. The initialization of shoppingList could have been written in a shorter form:
var shoppingList = ["Bread", "Milk"]
All values in the array literal are of the same type, enabling Swift to infer that [String] is the correct type for the shoppingList variable.
Combining two existing arrays with compatible types using the addition operator (+) allows you to create a new array. Swift infers the new array's type based on the type of the two combined arrays.

Accessing and Modifying an Array

Access and modify an array through its methods and properties or by using subscript syntax.

An array's read-only count property provides the number of items in an array.
print("The shopping list contains \(shoppingList.count) items.")
// prints "The shopping list contains 2 items."
Use the Boolean isEmpty property as a shortcut when you want to know whether the count property is equal to 0.
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
// prints "The shopping list is not empty.

Sets

set stores distinct values of the same type in a collection with no defined ordering. Sets are used as an alternative to arrays when item order is not a concern or when you need to ensure that an item appears only once.
For a Swift set, write the type as Set<T> where T is the type that the set is allowed to store. Unlike arrays, there is no equivalent shorthand for sets.
You can create an empty set of a certain type using initializer syntax:
var letters = Set<Character>()
Based on the initializer type, Swift infers the type of the letters to be Set<Character>.
An array literal will also work as shorthand when initializing a set with one or more values as a set collection.
var names: Set<String> = ["David", "Susan", "Robert"]
When initializing the type of set with an array literal that contains values of the same type, it is not necessary to write the type of set. The initialization could have been written in a shorter form:
var names: Set = ["David", "Susan", "Robert"]
Because all values in the array literal are of the same type, Swift infers that Set<String>is the correct type to use for the names variable.

Accessing and Modifying a Set

The count and isEmpty properties work the same way with a set as they do with an array.
Calling the set's insert method adds a new item to a set.
names.insert("Paul")
You can remove an item from a set by calling the set's remove method. The item is removed if it's a member of the set, and the removed value is returned. It returns nil if the item is not contained in the set. Alternatively, use the set's removeAll() method to remove all of the items in a set.

The contains method tells you whether or not a particular item is present in the set.
if names.contains("James") {
print("James is here.")
} else {
print("James is not with us.")
}

Iterating Over a Set

You can iterate over the values in a set with a for-in loop.
for name in names {
print("\(name)")
}
Since Swift's Set type does not provide defined ordering, use the sorted() method to iterate over the values of a set in a specific order.
for name in names.sorted() {
print("\(name)")
}

Set Operations



Swift allows you to efficiently perform fundamental set operations, such as combining sets, determining which values two sets have in common, or determining whether two sets contain all, some, or none of the same values.

Fundamental Set Operations



The illustration below depicts sets a and b, and shows the results of various set operations, as represented by the shaded regions:
The intersection method creates a new set, with only the values common to both sets.
The symmetricDifference method creates a new set with values in either set, but not both.
The union method creates a new set with all of the values in both sets.
The subtracting method creates a new set with values not in the specified set.

For example, to combine the two sets:
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]

oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Set Membership and Equality



The illustration below depicts three sets: a, b, and c. The overlapping regions represent the elements that are shared among sets.
Set a is a superset of set b, because a contains all elements in b. 
Conversely, set b is a subset of set a, because all elements in b are also contained by a.
Sets b and c are disjointed with one another, because they share no elements in common.
"is equal" operator (==): Determines whether two sets contain all of the same values.
isSubset(of: ) method: Determines whether all of the values of a set are contained in the specified set.
isSuperset(of: ) method: Determines whether a set contains all of the values in a specified set.
isStrictSubset(of: ) or sStrictSuperset(of: ) method: Determines whether a set is a subset or superset of, but not equal to, a specified set.
isDisjoint(with: ) method: determines whether two sets have any values in common.
Spend a little time playing with the methods to learn and understand their functions.


Dictionaries

dictionary stores associations between keys of the same type and values of the same type, in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. A dictionary is used to look up values based on their identifiers, in much the same way that a real-world dictionary is used to look up the definition of a particular word.

Written in its entirety, a Swift dictionary's type is Dictionary<Key, Value>. Key indicates which type of value can be used as a dictionary key, and Value indicates which type of value the dictionary stores for those keys. The shorthand form for the type of a dictionary is [Key: Value].

As with arrays, initializer syntax is used to create an empty Dictionary of a specified type:var airports = [Int: String]()
In the dictionary airports, the keys are of type Int, and the values are of type String.


The Dictionary Literal

A dictionary literal provides a way to write in shorthand one or more key-value pairs as a Dictionary collection.
The key and value in each key-value pair are separated by a colon. The key-value pairs are written as a list, separated by commas, surrounded by a pair of square brackets.
The example below creates a dictionary in which the keys are three-letter codes, and the values are airport names:
var airports: [String: String] = ["TOR": "Toronto", "NY": "New York"]
As with arrays, it isn't necessary to write the type of the dictionary when initializing it with a dictionary literal whose keys and values have consistent types. The initialization of airports could have been written in a shorter form instead.
var airports = ["TOR": "Toronto", "NY": "New York"]
Because all keys and values in the literal share the same type, Swift can infer that [String: String] is the correct type to use for the airports dictionary.

Accessing and Modifying a Dictionary

The count and isEmpty properties also work for the dictionary. 
Add a new item to a dictionary using subscript syntax:
airports["LHR"] = "London"
Subscript syntax can be used to change the value associated with a particular key:
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed
Use a dictionary's updateValue method as an alternative to subscripting when setting or updating a key's value. The updateValue method returns the old value after performing an update:
let oldValue = airports.updateValue("New York", forKey: "NY")
Subscript syntax is also used to retrieve a value for a particular key from the dictionary.
let airportName = airports["NY"]
If the value for the requested key does not exist, Swift returns a value of nil.
Use subscript syntax to assign a value of nil to a key in order to remove a key-value pair from a dictionary.
airports["APL"] = "Apple"
airports["APL"] = nil
Alternatively, the removeValue(forKey: ) method removes a key-value pair from a dictionary, if the pair exists, and returns the removed value. nil is returned if no value exists.
if let removedValue = airports.removeValue(forKey: "NY") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary does not contain a value for NY.")
}

Iterating Over a Dictionary


Use a for-in loop to iterate over the key-value pairs in a dictionary. Each item in the dictionary is returned as a (key, value) tuple, which you can decompose into temporary constants or variables as part of the iteration:
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
In addition, accessing a dictionary's keys and values properties will retrieve an iterable collection of the dictionary's keys or values.
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}

for airportName in airports.values {
print("Airport name: \(airportName)")
}
Since Swift's Dictionary type does not have a defined ordering, use the sort() method on the dictionary's keys or values property to iterate over the keys or values in a specific order.



































Bu blogdaki popüler yayınlar

SDLC - Software Development Life Cycle

@SerializedName and @Expose annotations