Conditional branching, repetition, delayed execution, pattern matching Syntax that controls the execution flow of a program. There are conditional branching and repetition in the control of the control flow, and they can be combined and executed freely.
chapter5.swift
let value = 5
if value <= 4 {
print("value is 4 or less")
}else {
print("value is 5 or more")
}
Optional types are data types that allow variables to be assigned nil, while non-optional types cannot be assigned nil. Optional variables have a "?" Or "!" At the end of the data type.
chapter5.swift
let optionalA = Optional(1)
if let a = optionalA {
print("value is\(a)is")
}else {
print("Value does not exist")
}
let optionalB = Optional("b")
let optionalC = Optional("c")
if let b = optionalB, let c = optionalC{
print("value is\(b)When\(c)you know")
}else {
print("Absent")
}
The guard statement is a syntax that describes what to do if the conditions are not met. If the condition is not met, it is necessary to write a process to end the method, end the iterative process, or exit the scope.
Code that exits processing when the condition is not met using the guard statement
chapter5.swift
//guard conditional expression else{
//Statement executed when the conditional expression is false
//You need to exit to the scope statement where the guard statement is written
//}
func someFunction() {
let value = -1
guard value >= 0 else {
print("Value less than 0")
return
}
print(value)
}
someFunction()
chapter5.swift
func printIfPositive(_ a: Int) {
guard a > 0 else {
return
}
print(a)
}
printIfPositive(6)
What is the difference between a guard let statement and an if let statement? Variables and constants declared in the guard let statement can be used after the guard let statement.
chapter5.swift
func someFONCTION() {
let a :Any = 3
guard let int = a as? Int else {
print("a is not an Int type")
return
}
print("The value is of type Int\(int)is")
}
someFONCTION()
func checkInt(num:Int) {
guard num >= 0 else {
print("It's a minus")
return
}
print("Is a plus")
}
checkInt(num:-10)
checkInt(num:10)
chapter5.swift
let r = -1
switch r {
case Int.min ..< 0:
print("r is a negative number")
case 1 ..< Int.max:
print("r is a positive number")
default:
print("a is 0")
}
chapter5.swift
enum SomeEnum {
case foo
case bar
case baz
}
let foo = SomeEnum.foo
switch foo {
case .foo:
print(".foo")
case .bar:
print(".bar")
case .baz:
print(".baz")
}
chapter5.swift
let optionalP: Int? = 12
switch optionalP {
case .some(let a) where a > 10:
print("Value greater than 10\(a)Exists")
default:
print("Value does not exist or is less than 10")
}
let g = 1
switch g {
case 1:
print("Will be executed")
break
print("Not executed")
default:
break
}
Recommended Posts