관리 메뉴

찹모찌의 기록일지

class와 instance를 알아보자 & method를 알아보자 본문

CS공부 일지

class와 instance를 알아보자 & method를 알아보자

찹모찌 2023. 8. 25. 16:47

Swift에서 객체(objects)는 어떤 의미일까요?

다음은 Swift 공식 문서에서 알아볼 수 있는 구조체와 class의 정의입니다.

Note

An instance of a class is traditionally known as an object. However, Swift structures and classes are much closer in functionality than in other languages, and much of this chapter describes functionality that applies to instances of either a class or a structure type. Because of this, the more general term instance is used.

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/classesandstructures/

 

Documentation

 

docs.swift.org

Swift 공식 문서에서는 전통적으로 class의 instance를 객체라고 부른다고 하지만, Swift의 구조체와 class는 다른 언어들보다 기능적으로 가까이 있고, 이에 따라 Swift에서는 instance라는 용어를 사용한다. 라고 되어있습니다.

실제로 구조체 안에 method를 선언할 수 있기도 하고, protocol을 이용해 상속과 비슷한 동작을 낼 수도 있기도 하고, 캡슐화도 가능합니다. 구조체와 class의 차이점은 다른 포스팅에서 좀 더 자세히 다뤄보겠습니다.

이렇듯 Swift에서는 객체는 좀 더 넓은 의미에서 구조체와 class의 instance라고 표현되고 있습니다.

class와 instance

class라는 instance의 청사진을 만들면 그 청사진에 맞춰 instance를 생성하고 동작시킬 수 있습니다.


Method 알아보기

import UIKit

class Pen {
    private var position: CGPoint
    private var color: UIColor
    
    init(position: CGPoint, color: UIColor) {
        self.position = position
        self.color = color
    }
    
    static func red() -> Pen {
        return Pen(position: CGPoint.zero, color: UIColor.red)
    }
    
    static func blue() -> Pen {
        return Pen(position: CGPoint.zero, color: UIColor.blue)
    }
    
    func getColor() -> UIColor {
        return color
    }
    
    func draw() {
        // draw 동작
    }
    
    func moveTo(point: CGPoint) {
        position = point
    }
}

Pen class를 예시로 들어보겠습니다.

getColor, draw, moveTo는 instance method, red, blue는 type method 중에서도 static method입니다.

// instance method의 경우 aPen(예시)라는 instance를 생성 후 사용가능
    let aPen = Pen(position: CGPoint(x: 0, y: 0), color: UIColor.white)
    aPen.draw()
    print(aPen.getColor())
    aPen.moveTo(point: CGPoint(x: 1, y: 1))

// static method의 경우 instance를 생성하지 않고도 사용가능
    let redPen = Pen.red()
    let bluePen = Pen.blue()

위에서 red()나 blue()의 경우 static method로 선언하여 factory method로 활용하는 모습입니다.

따로 instance를 생성하지 않고 사용할 수 있습니다. 또한 static dispatch를 사용하기 때문에 컴파일 상 좋은 성능을 낼 수 있습니다.

하지만 멤버 변수에 접근이 불가능하기 때문에 사용할 때 용도를 잘 고려해서 설계를 할 수 있어야 합니다.

    // position변수 사용할 수 없음
    static func red() -> Pen {
        let initPosition = position
        return Pen(position: CGPoint.zero, color: UIColor.red)
    }
    // position변수 사용할 수 있음
    func draw() {
        let initPosition = position
    }

Swift로 어플리케이션을 사용하면서 class, instance, method는 필수불가결한 존재이기 때문에 한 번 개념을 정리해봤습니다.

용도에 맞춰 잘 활용하는것이 좋은 어플리케이션을 만드는데 가장 중요한 것 아닐까 싶습니다.