본문 바로가기

programmer '프로그래머'

'if-else' 문에 대한 예시 코드

기본적인 'if' 문

let temperature = 30

if temperature > 25 {
    print("It's hot outside.")
}

위 예제에서는 'temperature' 가 25보다 클 경우 "lt's hot outside."라는 메시지가 출력됩니다.

'if-else' 문

let temperature = 20

if temperature > 25 {
    print("It's hot outside.")
} else {
    print("It's not that hot outside.")
}

이 예제에서는 'temperature' 가 25보다 크지 않기 떄문에 "lt's not that hot outside"라는 메시지가 출력됩니다.

'else-if' 문

let temperature = 15

if temperature > 25 {
    print("It's hot outside.")
} else if temperature < 10 {
    print("It's cold outside.")
} else {
    print("The weather is nice.")
}

이 예제에서는 'temperature' 가 25보다 크지 않고 10보다는 작지 않기 떄문에 "The weather is nice"라는 메시지가 출력됩니다.

복수 조건 사용

복수의 조건을 조합하여 'if' 문을 사용할 수도 있습니다.

let temperature = 18
let isRaining = true

if temperature > 25 && !isRaining {
    print("It's a great day for the beach!")
} else if temperature > 25 && isRaining {
    print("It's warm, but don't forget your umbrella.")
} else if temperature < 10 || isRaining {
    print("You might want to stay inside.")
} else {
    print("The weather is nice.")
}

이 예제에서는 'temperature' 가 25도보다 크지 않고 비가 오기 떄문에 "You might want to stay inside."라는 메시지가 출력됩니다.

위의 예제들이 스위프트에서 'if' 문을 사용하는 일반적인 방법입니다. 'if' 문을 사용하여 조건에 따라 다양한 로직을 구현할 수 있습니다.

'programmer '프로그래머'' 카테고리의 다른 글

옵셔널 사용한 예시  (0) 2024.08.30
Array 를 사용하는 예시 코드  (0) 2024.08.29
함수의 Swift구현 입니다.  (0) 2024.08.27
Call by Value/Call by Reference  (0) 2024.08.21
Foundation,UIKit '프레임워크'  (0) 2024.08.19