본문 바로가기
iOS

Swift: A Swift Tour - Control Flow

by Dev Arthur 2023. 4. 10.

<Control Flow>

  • Use if and switch to make conditionals, and use for-in, while, and repeat-while to make loops.
    = 'if'와 'switch'를 사용해서 조건을 만들고, 'for-in', 'while', 그리고 'repeat-while'를 사용해서 루프를 만든다
  • Parentheses around the condition or loop variable are optional.
    = 조건이나 루프 변수 주위의 괄호는 선택사항이다
  • Braces around the body are required.
    = 바디 부분을 둘러싼 중괄호는 필수다
  • In an if statement, the conditional must be a Boolean expression
    = if 구문에서 조건은 불리언 표현식이어야한다(true 혹은 false의 결과 값)
  • You can use if and let together to work with values that might be missing.
    = 'if'와 'let'을 함께 사용해서 누락됐을 수도 있는 값으로 작업할 수 있다
  • These values are represented as optionals.
    = 이 값들은 '옵셔널'이라고 표현된다
  • An optional value either contains a value or contains nil to indicate that a value is missing.
    = 옵셔널 값은 값을 포함하거나 값이 누락되었음을 가리키는 'nil'을 포함한다
  • Write a question mark (?) after the type of a value to mark the value as optional.
    = 값의 타입 뒤에 물음표를 사용해서 그 값이 옵셔널인 것을 표시한다
  • ex)
var optionalValue : String? = "hello"

if let value = optionalValue {
    print(value)
}
//value

optionalValue = nil

if let value = optionalValue {
    print(value)
}
else{
    print("fail")
}
//fail
//else 절이 없다면 아무것도 실행되지 않는다
  • If the optional value is nil, the conditional is false and the code in braces is skipped.
    = 만약 옵셔널 값이 nil이라면 조건은 false이기에 중괄호의 코드는 스킵된다
  • Otherwise, the optional value is unwrapped and assigned to the constant after let, which makes the unwrapped value available inside the block of code.
    = 옵셔널 값이 nil이 아니라면, 그 값은 let 뒤의 상수에 할당되어 언래핑되고 코드 블록 내에서 사용할 수 있게 된다
    ※ 언래핑: 옵셔널 값에서 값을 사용하기 위해 옵셔널이라는 랩을 벗겨내는 것, 그래서 옵셔널 언래핑이라고 한다
    옵셔널을 벗겨내지 않고 값을 사용하게 되면 컴파일러가 오류를 뱉어내기 때문에 옵셔널 값은 언래핑 해줘야한다
    옵셔널 언래핑에는 여러가지 방법이 있다
  • Another way to handle optional values is to provide a default value using the ?? operator.
    = 옵셔널 값을 다루는 또 다른 방법으로는 '??' 연산자를 사용해서 디폴트 값을 제공하는 방법이 있다
  • If the optional value is missing, the default value is used instead.
    = 만약 옵셔널 값이 누락되었다면, 디폴트 값이 대신 사용된다
  • ex)
var optionalValue : Int? = nil
var defaultValue : Int = 100
var newValue = optionalValue ?? defaultValue

print(newValue)
// 100
  • You can use a shorter spelling to unwrap a value, using the same name for that unwrapped value.
    = 언래핑할 값과 동일한 이름을 사용해서 더 짧게 값을 언래핑 가능하다
    ※ 오류나서 안된다... => 확인 결과, swift 5.7 버전 이후부터 사용 가능하다
  • ex)
var optionalValue : Int? = nil

if let value = optionalValue{
    print(value)
}
else{
    print("fail")
}
// fail

if let optionalValue { 
    print(optionalValue)
}
else{
    print("fail")
}
// swift 5.7 버전 부터 사용 가능해서 그 이전 버전에는 오류 발생
// Error: Variable binding in a condition requires an initializer
  • Switches support any kind of data and a wide variety of comparison operations.
    = 스위치는 모든 형식의 데이터와 다양한 비교 작업을 지원한다
  • ex)
let number = "230411"

switch number {
case "230409":
    print("230409")
case "230408", "230411":
    print("230408 or 230411")
case let x where x.hasSuffix("10"):
    print("Today")
default:
    print("no day")
}
  • Notice how let can be used in a pattern to assign the value that matched the pattern to a constant.
    = 패턴과 일치하는 값을 상수에 할당하기 위해 패턴에서 let이 어떻게 사용될 수 있는지 주목해라
    ※ 여기서 패턴이라는 건, case 문의 조건을 얘기하는 걸까...?
  • After executing the code inside the switch case that matched, the program exits from the switch statement.
    = switch의 일치하는 case 안의 코드가 실행되고 난 뒤에는, 프로그램은 switch 문을 종료한다
  • Execution doesn’t continue to the next case, so you don’t need to explicitly break out of the switch at the end of each case’s code.
    = (일치하는 case의 코드의)실행은 다음 case로 이어지지 않기에, 각 case의 코드 끝마다 명시적으로 중단할 필요가 없다
    ※ 다음 case의 조건으로 이어지게 하고싶다면 case의 코드 끝에 'fallthrough'를 사용하면 된다
  • You use for-in to iterate over items in a dictionary by providing a pair of names to use for each key-value pair.
    = 'for-in'문을 사용해서, 각 키-값 쌍에 사용할 이름의 쌍을 제공을 통해 딕셔너리의 아이템들을 순회할 수 있다
  • Dictionaries are an unordered collection, so their keys and values are iterated over in an arbitrary order.
    = 딕셔너리는 순서 없는 콜렉션이기 때문에, 딕셔너리의 키-값은 임의의 순서로 순회된다
  • ex)
let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (_, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
print(largest)
// 25
  • Use while to repeat a block of code until a condition changes. 
    = 'while'문을 사용해서, 조건이 바뀔때까지 코드 블록을 반복할 수 있다
  • The condition of a loop can be at the end instead, ensuring that the loop is run at least once.
    = 루프의 조건을 끝에 둬서, 루프가 적어도 한 번은 실행될 수 있도록 할 수 있다
  • ex)
<루프의 조건이 앞에 있는 경우>
var num1 = 0
var count1 = 0
while num1 < 10{
	num1 += 1
	count1 += 1
}
print(count1)
// 10

num1 = 10
count1 = 0
while num1 < 10{
	num1 += 1
	count1 += 1
}
print(count1)
// 0

<루프의 조건이 끝에 있는 경우>
var num2 = 0
var count2 = 0
repeat {
    num2 += 1
    count2 += 1
} while num2 < 10
print(count2)
// 10

num2 = 10
count2 = 0
repeat {
    num2 += 1
    count2 += 1
} while num2 < 10
print(count2)
// 1
  • You can keep an index in a loop by using ..< to make a range of indexes.
    = 인덱스의 범위를 만들기 위해 '..<'를 사용해서, 루프에서 인덱스를 사용할 수 있다
  • ex)
var num = 0
var count = 10

for i in 0..<10{
	num += i
}
print(num)
// 45
  • Use ..< to make a range that omits its upper value, and use ... to make a range that includes both values.
    = '..<' 기호를 사용해서 '하위 값 이상 상위 값 미만', '...' 기호를 사용해서 '하위 값 이상 하위 값 이하'를 만든다
반응형

'iOS' 카테고리의 다른 글

Swift: A Swift Tour - Objects and Classes  (0) 2023.07.13
Swift: A Swift Tour - Functions and Closures  (0) 2023.04.25
Xcode: 설치하기  (0) 2023.04.13
Swift: A Swift Tour - Simple Values  (0) 2023.04.07
Swift: About Swift  (0) 2023.04.06