2. Control Flow:
There are three main types of statements
About IF
The conditions in the statement no longer require the use of () packages.
1234 |
let number = 23 if number < 10 { print( "The number is small" ) } |
However, the code behind the judgment execution must be wrapped with {}.
The condition after the if must be a Boolean expression
That is, it is not implicitly compared to 0, which is wrong, because number is not a Boolean expression, number! = 0 is.
123 |
int number = 0 if number{ } |
About for
The For loop becomes more convenient and more powerful in Swift.
Benefit from Swift's newly added range operator ... and ...<
We are able to use the tedious for loop:
1234 |
for (int i = 1; i <= 5; i++) { NSLog(@ "%d" , i); } |
Overwrite to:
123 |
for index in 1...5 { print(index) } |
Although no similar usage is mentioned in the Swift programming Language, we have an elegant approach in swift.
123 |
for index in stride(from: 1, through: 5, by: 2) { print(index) } // through是包括5 |
Then the traversal of the dictionary is enhanced. In the fast enumeration of objective-c we can only enumerate the keys of the dictionary.
1234 |
NSString *key; for (key in someDictionary){ NSLog(@ "Key: %@, Value %@" , key, [someDictionary objectForKey: key]); } |
In Swift, through tuple we can enumerate both key and value:
1234 |
let dictionary = [ "firstName" : "Mango" , "lastName" : "Fang" ] for (key,value) in dictionary{ print(key+ " " +value) } |
About switch:
Swich also gained enhanced functionality and increased security in swift.
No break is required to terminate the next case execution
That is, the following two types of notation are equivalent.
123456789 |
let character =
"a"
switch
character{
case
"a"
:
print(
"A"
)
break
case
"b"
:
print(
"B"
)
break
default
: print(
"character"
)
|
1234567 |
let character =
"a"
switch
character{
case
"a"
:
print(
"A"
)
case
"b"
:
print(
"B"
)
default
: print(
"character"
)
|
This improvement avoids forgetting to write the error caused by the break, I have a deep experience, it was because of the omission of the write-off and spent a period of time to debug.
If we want to treat different values uniformly, separate the values with commas.
1234 |
switch some value to consider { case value 1,value 2: statements } |
In Swift, the type of switch support has been greatly broadened.
This means that in development we are able to match strings, floating-point numbers, and so on.
Previously, the tedious wording of OC could be improved:
123456789 |
if
([cardName isEqualToString:@
"Six"
]) {
[self setValue:6];
}
else
if
([cardName isEqualToString:@
"Seven"
]) {
[self setValue:7];
}
else
if
([cardName isEqualToString:@
"Eight"
]) {
[self setValue:8];
}
else
if
([cardName isEqualToString:@
"Nine"
]) {
[self setValue:9];
}
|
12345678910 |
switch
carName{
case
"Six"
:
self.vaule = 6
case
"Seven"
:
self.vaule = 7
case
"Eight"
:
self.vaule = 8
case
"Night"
:
self.vaule = 9
}
|
Swift Learning (II.)