Apple-CS-interview / iOS-CS-interview

7 stars 0 forks source link

Struct 가 무엇이고 어떻게 사용하는지 설명하시오. #7

Open Do-hyun-Kim opened 1 year ago

vichye-1 commented 1 year ago

Struct 는 Class 와 공통점이 많다

Class는 구조체에 없는 추가적인 기능이 있다.

이처럼, Class가 지원하는 기능이 Struct에 비해 많기 때문에, 복잡성이 증가한다.

Struct 정의 구문

struct SomeStructure {
// structure definition goes here
}

let originalLang = Study()


### 프로퍼티 접근
 - dot syntax(점 구문)로 인스턴스의 프로퍼티에 접근할 수 있다.
```swift
print("I studied \(originalLang.language) for \(originalLang.month) months")

// I studied Python for 12 months

멤버별 초기화 구문

print("I studied (anotherLang.language) for (anotherLang.month) months")

// I studied Swift for 2 months



### 📝 참고

- https://docs.swift.org/swift-book/documentation/the-swift-programming-language/classesandstructures/
- https://developer.apple.com/documentation/swift/choosing-between-structures-and-classes
ronick-grammer commented 1 year ago

Struct란

Struct 정의

struct Person {
    var name: String
    var age: Int

     func greet() {
        print("Hello, I'm \(name) and I'm \(age) years old.")
    }

struct 메서드 내에서 프로퍼티를 변경하고자 할때에는 mutating 키워드를 사용한다.

mutating func greet() {
     self.name = "이름"
}

참조타입이 아닌 값 타입을 사용해야 하는 경우

하나의 인스턴스를 공유해야 하는 경우가 아니라 각각의 인스턴스를 사용해야 하는 것이 합당하면 struct 를 사용한다. 아래의 예시는 참조타입인 class 였다면 하나의 인스턴스를 공유하지만, struct 이기에 값 복사가 이루어져 다른 인스턴스를 사용하게 된다.

// create an instance of Person
var person1 = Person(name: "Alice", age: 25)

// create another instance by copying person1
var person2 = person1

// modify person2's name
person2.name = "Bob"

// print person1's name
print(person1.name) // Alice

// print person2's name
print(person2.name) // Bob

Swift 에서 Struct를 사용해야만 하는 주요 이유

Swift 에서 structclass 가 가지는 거의 모든 기능을 제공하고 있다.

하지만, class 가 가지는 OOP 로서의 중요한 '상속' 기능을 지원하고 있지는 않다. 상속이 OOP 관점에서 중요한 이유는 부모 클래스로부터 물려받는 메서드와 프로퍼티들이 재사용 가능하며, 이들을 overriding 하여 다형성을 구현할 수 있기 때문이다.

struct로 구현하는 다형성과 POP(Protocol Oriented Programming)

Swift 언어가 공식적으로 지향하는 프로그래밍 패러다임이 있는데 이가 바로 '프로토콜 지향 프로그래밍(POP)' 이다. POP 는 참조타입은 class 보다 값타입인 struct 를 지향하는 프로그래밍 패러다임이다. 참조 타입으로부터의 오류 최소화와 자요로움을 추구한다. POP의 특징은 아래와 같다.

POP를 적극 활용하면 상속을 지원하지 않는 struct에서도 다형성을 충분히 구현할 수 있게 된다.

// define a protocol for vehicles
protocol Vehicle {
    // define some properties
    var currentSpeed: Double { get set }

    // define some methods
    func start()
    func stop()
}

extension Vehicle {
    func start() {
        print("Starting...")
    }

    func stop() {
        print("Stopping...")
    }
}

struct Car: Vehicle {
    var currentSpeed = 0.0

    mutating func stop() {
        print("Stopping...(overriding)")
        currentSpeed = 0
    }

    func honk() {
        print("Beep beep!")
    }
}

var car = Car()

car1.start() // "Starting..."
car1.stop() // "Stopping...(overriding)"

car1.honk() // "Beep beep!"

📝 참고 사이트

Do-hyun-Kim commented 1 year ago

Struct 가 무엇이고 어떻게 사용하는지 설명하시오

Thread Safe

Race Condition

Struct 를 사용해야하는 이유

// 권장되지 않는 방식
struct Complex {
    private var real: Double
    private var imaginary: Double

    init(real: Double, imaginary: Double) {
        self.real = real
        self.imaginary = imaginary
    }

    // 자기 자신의 프로퍼티를 변경하려 할 경우 mutating 키워드를 추가해야 합니다.
    mutating func add(_ complex: Complex) {
        real += complex.real
        imaginary += complex.imaginary
    }
}
struct Complex {
    private let real: Double
    private let imaginary: Double

    init(real: Double, imaginary: Double) {
        self.real = real
        self.imaginary = imaginary
    }

    func plus(_ complex: Complex) -> Complex {
        return Complex(real: real + complex.real, imaginary: imaginary + complex.imaginary)
    }
}

📝 참고 사이트

Hminchae commented 1 year ago

Struct

Struct 사용 이유

이럴 때 Struct 를 쓰세요!

다른언어와 다르게 스위프트의 구조체는 클래스에서 사용할 수 있는 다양한 요소들을 사용할 수 있고 , Class보다 복잡성이 적기 때문에 디폴트로 구조체를 사용하기를 공식문서에서도 권장하고 있음

📝 참조