반응형
Notice
Recent Posts
Recent Comments
Link
Today
Total
07-05 05:44
«   2024/07   »
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
Archives
관리 메뉴

iOS 개발 기록 블로그

iOS(Swift) 구조체(struct) 사용 방법 본문

iOS

iOS(Swift) 구조체(struct) 사용 방법

crazydeer 2022. 5. 20. 09:00
반응형

Swift에서도 역시 구조체(struct)가 있고 그 사용 방법에 대해 알아보자.

 

개념

스위프트에서 데이터 타입은

Int, Float, String, Boolean, Array, Dictionary 등

여러 가지가 존재한다.

 

우리는 직접 개인화(커스터마이징)한 데이터 구조체를 만들 수 있다.

그걸 구조체, structure, struct, class(?)라고 부른다.

 

 

코드

먼저 예시 코드를 보자.

// custom data type
struct Town {
    // Properties
    let name = "CdeerLand"
    var citizens = ["Cdeer", "SunnyAn"]
    var resources= ["Grain": 100, "Ore": 42, "Wool": 75]
    
    // Method
    func fortify() {
        print("Defences increased!")
    }
}
 
var myTown= Town()
print(myTown.resources["Ore"]!)

Town이라는 구조체를 위와 같이 만든다.

변수 하나하나들을 Property라고 하고

구조체 안에 있는 함수를 Method라고 한다.

 

myTown이라는 변수를 만들고 일반 함수처럼 Town()를 써서 사용할 수 있다.

이는 코드를 관리하고 사용하기 효율적이고 용이하게 해 준다.

 

 

예시

차의 설계도(blueprint)를 만든다고 생각해봐라.

 

// Property

color가 들어갈 수 있고 (검은색, 흰색, 빨간색 등)

type이 들어갈 수도 있다. (해치백, 세단, SUV 등)

 

// Method

func drive() {
    // car moves forwards
}

 

즉, 프로퍼티는 어떤 데이터가 어떤 형태로 들어가는지,

메서드는 무슨 기능을 하는지 나타낸다.

 

실제 사용하기 위해

이 하나의 설계도(구조체)를

실제 Object에 초기화(init() = initialize)해줘야 한다.

 

이 과정이 바로 아래 코드 라인이다.

var myTown= Town()

 

 

일반적인 사용 예시

일반적으로는 아래와 같이 사용한다.

// custom data type
struct Town {
    // Properties
    let name: String
    var citizens: [String]
    var resources: [String: Int]
    
    init(townName: String, people: [String], stats: [String: Int]) {
        name= townName
        citizens= people
        resources= stats
    }
    
    // Method
    func fortify() {
        print("Defences increased!")
    }
}
 
var anotherTown= Town(townName: "Nameless Island", people: ["Tom Hanks"], stats: ["Coconuts": 100])
 
anotherTown.citizens.append("Wilson")
print(anotherTown.citizens)

결과: ["Tom Hanks", "Wilson"]

 

위 코드처럼 init 구조체 안에 넣어처음에 실제 객체를 생성할 때 값들을 입력해서 초기화한다.

 

 

self. 를 쓰는 이유

그런데 위와 같이 구조체 안에 프로퍼티 이름(name, citizens, resources)과입력받는 이름(townName, people, stats)이다르면 헷갈릴 수 있다.

그래서 같게 해 주면 아래처럼 에러가 난다.

구조체 사용 시 에러

그래서 일반적으로 앞에 self. 를 붙여준다.

구조체 사용 시 에러 해결

 

 

 

최종 이미지

구조체 사용법 최종 이미지

 

 

참고

안젤라유 강의: https://www.udemy.com/course/ios-13-app-development-bootcamp/

 

iOS & Swift - The Complete iOS App Development Bootcamp

From Beginner to iOS App Developer with Just One Course! Fully Updated with a Comprehensive Module Dedicated to SwiftUI!

www.udemy.com

 

반응형