ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [TIL w2d1] Swift 복습 (Tuple, Collection Type, Closure)
    iOS💖 2025. 3. 10. 21:17

    [Today's Word]

    오늘의 할 일을 내일로 미루지 말자.

     

    [강의내용]

    1. 오늘 배운 것

    • 변수, 상수
    • 주석
    • 기본 데이터 타입 (Int, Float, Double, String, Character, Boolean, Tuple)
    • Swift Convention Guid No. 1, 2, 3
    • 연산자 (대입, 산술, 비교, 논리, 범위, 삼항)
    • 조건문 (if, guard, switch)
    • 반복문 (for, while, break, continue)
    • 함수
    • Collection Type (Array, Set, Dictionary)
    • Closure

     

     

    2. 개념 정리

    오늘 배운 것 중, 기존 알고 있던 개념에 +@ 된 내용 만 정리하였다.   

     

    1. Swift Convention Guid
    2. 기본 데이터 타입
      1. Int
      2. Float : 소수점 아래 6자리까지
      3. Double : 소수점 아래 15자리까지
    3. Tuple : (하나의 타입처럼 사용 가능)
    4. Switch : fallthrough
    5. Array : .append(contentsOf: [])
    6. Set : 집합
    7. Dictionary
    8. Closure : Optional Closure, Trailing Closure 🔴

     

     

    1. Swift Convention Guid

    컨벤션이란, 코드를 작성할 때 지키면 좋은 통일된 규칙을 의미한다.

    통일 된 규칙이 있으면 다른 사람이 작성한 코드를 빠르게 이해할 수 있다.

    1. 이름 짓는 방법 : Camel Case 
    2. 변수와 상수 이름 짓기 : 변수의 이름은 소문자로 시작
    3. :  컨밴션 : 타입을 정하는 :  앞에는 공백이 없고 뒤에는 공백이 있게 코드를 작성
    4. 연산자 코드 컨밴션 : 논리연산자 NOT을 제외한 
    					AND, OR, 대입 연산자 , 산술 연산자, 비교 연산자 양옆으로 공백
    5. 함수의 코드 스타일 : 함수 / 매개변수 이름은 Camel Case

     

     

     

    2. 기본 데이터 타입 (Int, Float, Double)

    • Int (정수형)
      • 범위 : -2,147,483,648 ~ 2,147,483,647 
    • Float
      • 32 bit 메모리 공간 차지, 소수점 아래 6자리까지 표현 가능
    • Doublt
      • 64 bit 메모리 공간 차지, 소수점 아래 15자리까지 표현 가능

     

     

    3. Tuple

    • 데이터 타입의 값들을 그룹화하여 -> 하나의 타입처럼 사용 가능
    • 고유 인덱스 가짐
    let hakyung: (name: String, age: Int, major: String) = ("hakyung", 30, "iOS")
    let student: [(name: String, age: Int, major: String)] = [
        ("haykung", 20, "iOS"),
        ("sam", 21, "Web"),
        ("Mei", 19, "Server")
    ]
    
    print(student[1])

     

     

     

     

    4. Switch

    • fallthrough
      • case 에서 조건이 맞아서 실행된 후, 아래의 조건도 확인하고 싶을때 사용

     

     

     

    5. Array

    • .append(contentsOf: [])
      • 배열 안에 배열 추가
    var array = [0, 1, 2, 3]
    array.append(contentsOf: [10, 20, 30])
    
    print(array) // [0, 1, 2, 3, 10, 20, 30]

     

     

     

     

    6. Set (집합)

    • 순서 x
    • 중복 x
    • 타입 명시!
    var stringSet: Set<String> = []
    var intSet: Set<Int> = Set()
    
    print(stringSet.contains("a"))
    
    intSet.insert(1)
    print(intSet)
    
    
    // 2. Set 실습하기 : 아래를 코드로 만들어주세요.
    var setSet: Set = ["1", "2", "3"]
    setSet.insert("3")
    
    print(setSet)
    
    let isFourContain = setSet.contains("4")
    print(isFourContain)
    
    setSet.remove("1")
    print(setSet)

     

     

     

     

    7. Dictionary

    • 순서 x
    • 형태 : key: value
    • key 중복 x
    var dictionary = [String: String]()
    //var dictionary: [String: String] = [:]
    
    dictionary["A"] = "Apple"
    dictionary["B"] = "Banana"
    print(dictionary["A"])
    
    dictionary["A"] = "Avocado"
    print(dictionary["A"])
    
    print(dictionary.count)

     

     

     

     

    8. Closure

    • 파라미터: 튜플타입 (Int, String), 반환타입은 없음!
    let closure: (Int, String) -> Void = { intValue, stringValue in
        print(intValue)
        print(stringValue)
    }
    closure(40, "이거 읽어봐")

     

     

    • 파라미터의 이름을 생략하 구현부에서 $0로 사용할 수 있다.
    let closure2: (Int) -> Void = {
        print($0)
    }
    closure2(1004)
    let closure5: (String, Int) -> Int = {
        return $0.count + $1
    }
    print(closure5("200", 3))

     

     

    • 파라미터 없는 클로저
    let closure3: () -> Void = {
        print("Hello!")
    }
    closure3()

     

     

    • 파라미터 Int, output Int
    let closure4: (Int) -> Int = { value in
        return value * 2
    }
    print(closure4(10))

     

     

    • Optional Closure
    let optionalClosure: ((Int) -> Int)? = { value in
        return value * 2
    }
    print(optionalClosure!(40))

     

     

    • 파라미터가 없을 때는 in을 사용하면 안됨
    let emptyParameterClosure: () -> Void = {
        print("Hello Im Emmpty")
    }
    emptyParameterClosure()

     

     

     

    8.1. Trailing Closure 🔴

    : 경량화 방법 중 하나

    func trailingCloure(key: String, closure: () -> Void) {
        print(key)
        closure() // ⭐️
    }

     

    • 클로저가 마지막 파라미터일때, 이어서 작성
    trailingCloure(key: "trailing Closure Test1", closure: {
        print("The Closure in 'trailing Closure Test1'")
    })

     

     

    • 클로저 구현이 길어지는 경우, 클로저함수호출 외부에 작성하여, 가독성 높이기
    trailingCloure(key: "trailing Closure Test2") {
        print("Second trailing Closure")
    }

     

     

     

     

     

     

     

    [깃헙 코드]

    https://github.com/hortenssiaa/SpartaCamp-iOS/blob/main/Nbc-Swift-Grammer/Swift-Grammer-week-1.swift

     

    SpartaCamp-iOS/Nbc-Swift-Grammer/Swift-Grammer-week-1.swift at main · hortenssiaa/SpartaCamp-iOS

    deep dive ❤️‍🔥 into iOS. Contribute to hortenssiaa/SpartaCamp-iOS development by creating an account on GitHub.

    github.com

     

    댓글

Designed by black7375.