티스토리 뷰

출처

http://kka7.tistory.com/7



흐름제어

Swift 의 for-in 문은 array, dictionary, range, string, sequences 에서의
반복을 쉽게해준다.

switch 의 case 는 다음 case 로 넘어가지 않는다.
일반적인 C 에서 break 문을 빼먹는 실수로 발생되는 오류를 피하게해준다.




For Loop


for index in 1...5 {

    print("\(index) times 5 is \(index * 5)")

}



특별히 index 가 필요없다면 

아래와 같이 ( _ ) 언더바를 이용할 수 있다.


let base = 3

let power = 10

var answer = 1


for _ in 1...power {

    answer *= base

}


print("\(base) to the power of \(power) is \(answer)")



배열의 아이템을 반복할 때 for - in 을 사용한다.


let names = ["Anna", "Alex", "Brian", "Jack"]


for name in names {

    print("Hello, \(name)!")

}



dictionary 의 key-value 에 접근하기 위해 아래와 같이 사용한다.


let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]


for (animalName, legCount) in numberOfLegs {

    print("\(animalName)s have \(legCount) legs")

}





while

일반적인 while 문과 동일하게 사용된다.

while condition {

    statements

}



do-while 대신 repeat-while 을 사용한다.


repeat {

    statements

} while condition






If-Else

if-else 의 경우 다른 언어와 다른 점이 있다면, 
if 내부 조건문이 무조건 true 여야 한다는 점이다.

즉, count 가 0 이상이라고 해서
아래와 같이 코딩할 수 없다.

var count = 3

if count {

    

}





Switch

default 값을 무조건 정의되어야하며,
case 에 해당하면 자동으로 아래 조건을 검사하지 않는다.


let someCharacter: Character = "z"


switch someCharacter {

case "a":

    print("The first letter of the alphabet")

case "z":

    print("The last letter of the alphabet")

default:

    print("Some other character")

}



이전에 case 를 중첩해서 사용하던 것을 

swift 에서 사용하려면 아래와 같이 한다.


let anotherCharacter: Character = "a"


switch anotherCharacter {

case "a", "A":

    print("The letter A")

default:

    print("Not the letter A")

}



간격 일치

switch 조건에서 값은 간격이 포함되었는지 확인할 수 있다.

let approximateCount = 62

let countedThings = "moons orbiting Saturn"

var naturalCount: String


switch approximateCount {

case 0:

    naturalCount = "no"

case 1..<5:

    naturalCount = "a few"

case 5..<12:

    naturalCount = "several"

case 12..<100:

    naturalCount = "dozens of"

case 100..<1000:

    naturalCount = "hundreds of"

default:

    naturalCount = "many"

}


print("There are \(naturalCount) \(countedThings).")



튜플 사용하기

여러개의 값을 테스트하기 위해 튜플을 사용할 수 있다.
튜플의 각 요소는 다른 값이나 값의 간격을 테스트할 수 있다.
대신, 가능한 모든 값과 일치하기 위한
와일드카드 패턴으로 알려진 ( _ ) 를 사용한다.

let somePoint = (1, 1)


switch somePoint {

case (0, 0):

    print("(0, 0) is at the origin")

case (_, 0):

    print("(\(somePoint.0), 0) is on the x-axis")

case (0, _):

    print("(0, \(somePoint.1)) is on the y-axis")

case (-2...2, -2...2):

    print("(\(somePoint.0), \(somePoint.1)) is inside the box")

default:

    print("(\(somePoint.0), \(somePoint.1)) is outside of the box")

}


여러개 일치가 가능할 경우

가장 처음 일치되는 case 문이 사용된다.



값 바인딩

일치하는 값들을 case 본문에서 사용하기 위해
임시 상수나 변수로 묶을 수 있다.

let anotherPoint = (2, 0)


switch anotherPoint {

case (let x, 0):

    print("on the x-axis with an x value of \(x)")

case (0, let y):

    print("on the y-axis with a y value of \(y)")

case let (x, y):

    print("somewhere else at (\(x), \(y))")

}



where

case 문 내부에서 추가적인 case 를 확인하고 싶을 때 where 를 사용한다.

let yetAnotherPoint = (1, -1)


switch yetAnotherPoint {

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")

}




복합 조건

case 이후에 몇가지 패턴을 콤마 ( , ) 로 구분해서 작성하여

동일한 본문을 공유하는 여러 개의 switch case 가 결합된다.


let someCharacter: Character = "e"


switch someCharacter {

case "a", "e", "i", "o", "u":

    print("\(someCharacter) is a vowel")

case "b", "c", "d", "f", "g",

     "h", "j", "k", "l", "m",

     "n", "p", "q", "r", "s",

     "t", "v", "w", "x", "y", "z":

    print("\(someCharacter) is a consonant")

default:

    print("\(someCharacter) is not a vowel or a consonant")

}






Fallthrough

일반적인 Objective-C 처럼 switch 문에서 fallthrough 가 되기를 바란다면
fallthrough 키워드를 이용하여 작성한다.


let integerToDescribe = 5

var description = "The number \(integerToDescribe) is"


switch integerToDescribe {

case 2, 3, 5, 7, 11, 13, 17, 19:

    description += " a prime number, and also"

    fallthrough

default:

    description += " an integer."

}





Label 구문

중첩된 반복문과 다른 반복문 내의 조건문, 복잡한 조건을 제어하는 구조를 만들 수 있다.
반복문에 레이블된 구문의 실행을 종료하거나 계속 수행하기 위해
break, continue 문과 함께 구문 레이블을 사용할 수 있다.

var i = 0

var j = 0


outer: for i in 2..<10 {

    inner : for j in 2..<10 {

            print("test i : \(i) / j : \(j)")

            if j == 8 {

                break outer

            }

    }

}





guard

guard 는 if 문과 비슷하며 표현식의 Boolean 값을 확인하여 실행한다.
guard 문 뒤에 코드가 실행하도록 반드시 true 인 조건이 필요한 경우 사용한다.
if 와는 다르게 guard 문은 항상 else 절을 가져야한다.

모든 변수나 상수의 값은 옵셔널 바인딩을 사용하여 할당되며
guard 코드 블럭에 나머지 조건을 나타낼 수 있다.

또한 else 에서는 return, break, continue, throw, fatalError 와 같은 
반환하지 않는 함수나 메소드를 호출해야한다.


func greet(person: [String: String]) {

    

    guard let name = person["name"]

        else {

            return

    }

    

    print("Hello \(name)!")

    

    guard let location = person["location"]

        else {

            print("I hope the weather is nice near you.")

            return

    }

    

    print("I hope the weather is nice in \(location).")

}



greet(person: ["name": "John"])

// Prints "Hello John!"

// Prints "I hope the weather is nice near you."


greet(person: ["name": "Jane", "location": "Cupertino"])

// Prints "Hello Jane!"

// Prints "I hope the weather is nice in Cupertino."





#available

API 가 사용가능한지 확인하는 것을 기본으로 제공한다.

배포 대상에서 사용할 수 없는 API 를 사용하지 않는 것을 보장한다.


조건문 코드 블럭 실행을 위해 if 나 guard 로 가용조건을 확인하며

사용하고자하는 API 가 실행 중에 사용할 수 있는지를 확인한다.


if #available(iOS 10, macOS 10.12, *) {

    // Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS 

} else {

    // Fall back to earlier iOS and macOS APIs 

}







공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함