반응형
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와 Class의 차이 본문

iOS

iOS(Swift) Struct와 Class의 차이

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

Struct vs Class

struct는 properties 값을 주지 않아도 된다.

그러나 class init을 해줘야 한다.

Enemy.swift (Class)

 

 

코드

class Enemy {
    // properties
    var health: Int
    var damage: Int
    
    init(health: Int, damage: Int) {
        self.health= health
        self.damage= damage
    }
    
    // functions (methods)
    func move() {
        print("Walk forwards.")
    }
    
    func attack() {
        print("Land a hit, does \(damage)damage.")
    }
}

 

이렇게 init을 해주면 된다.

 

그럼 Enemy 클래스에 takeDamage라는 함수를 만들어보자.

class Enemy {
    // properties
    varhealth: Int
    vardamage: Int
    
    init(health: Int, damage: Int) {
        self.health= health
        self.damage= damage
    }
    
    // functions (methods)
    func takeDamage(amount: Int) {
        health= health- amount
    }
    
    funcmove() {
        print("Walk forwards.")
    }
    
    funcattack() {
        print("Land a hit, does \(damage)damage.")
    }
}

 

이렇게 하면 될 것이고 메인에서 사용해보자.

 

 

 

skeleton1을 만들어주고

skeleton2를 skeleton1으로 만들어줬다.

 

이때 skeleton1에게 10만큼 데미지를 주고

skeleton2의 체력을 출력해봤더니 위와 같이 90이라고 찍혔다.

이는 skeleton2가 skeleton1을 참조하고 있어서

1의 프로퍼티가 변경되면 2도 따라 바뀌는 것이다.

 

 

Struct vs Class

위와 같이 새로 초기화를 해줘야

같은 오브젝트가 아닌 다른 오브젝트가 되어

각각 작용하게 된다.

 

 

Struct vs Class 2

 

이렇게 한 오브젝트를 가르키는 

skeleton1 skeleton2는 같이 값이 적용받는다.

이걸 struct로 바꿔보면 다음과 같다.

 

struct는 기본적으로 immutable(불변의)immutable(불변의) 하기 때문에

mutating func으로 바꿔줘야 프로퍼티를 변경할 수 있다.

 

Struct Error (immutable)

 

// functions (methods)
mutating func takeDamage(amount: Int) {
    health= health- amount
}

 

 

 

main.swift

 

Struct Error (immutable) 2

 

let 키워드를 쓸 수 없게 된다. 

따라서 var로 바꿔줘야 한다.

 

 

그런 다음에 실행해본다.

var 키워드 변경 후 error trouble shooting

 

skeleton2는 분리된 복제본으로 생성되었기 때문에

skeleton1에게 데미지를 줘도

skeleton2에게 반영되지 않는다.

 

아까 클래스의 경우 하나의 객체를 가리키는(참조하는) 것이고

구조체의 경우는 각각 다른 객체인 것이다.

 

 

결론

struct는 값에 의해 전달된다.

예를 들어 폴라로이드 사진을 찍었다고 생각해보자.

구조체는 사진의 복제된 또 다른 한 장을 주는 것이다.

 

클래스는 어떤 사진이 폴더 안에 있다고 생각해보자.

그 사진의 경로를 참조하는 것이다.

예를 들어 /Users/crazydeer/Desktop/My Images/이미지파일이름.png

를 찍는 것이고 따라서 이미지 파일이 변화하는 것에 영향을 받는다.

 

 

 

Apple의 권고사항 (advise)

https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html

 

 

 

 

참고

안젤라유 강의: 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

 

반응형