swift

swift - Inheritance and Polymorphism #4 (Overloading)

행복하게사는게꿈 2021. 1. 12. 14:59

overloading

// 하나의 형식에서 동일한 이름을 가진 다양한 메소드를 생성할때 사용
// 동일한 스코프에 동일한 이름의 메소드가 있으면 에러 발생

// 파라미터 형식이 달라지면 err가 사라진다.

// overloading Rule
// 1. 함수 이름이 동일하면 파라미터 수로 식별
// 2. 이름과 파라미터 수가 동일하면 파라미터 자료형으로 식별
// 3. 이름과 파라미터, 파라미터 자료형이 동일하면 Argument label로 식별
// 4. 이름, 파라미터, 파라미터 자료형, Argument Label이 동일하면 리턴형으로 식별


func process(value: Int) {
    print("process Int")
}

func process(value: String) {
    print("process String")
}

func process(value: String, anotherValue: String) {
    
}

func process(_ value: String) {
    
}

func process(value: Double) -> Int? {
    return Int(value)
}

func process(value: Double) -> String? {
    return String(value)
}


process(value: 0)
process(value: "String")

// 저장할 자료형을 명시해주지 않으면
// Ambiguous use of 에러가 발생한다.
let result: Int? = process(value: 12.34)
let result2 = process(value: 12.34) as Int?

let result3: String? = process(value: 12.34)
let result4 = process(value: 12.34) as String?

// 메소드, 생성자, subscript에서도 동일하게 수행
struct Rectangle {
    func area() -> Double {
        return 0.0
    }
    
    static func area() -> Double {
        return 0.0
    }
}

let r = Rectangle()
r.area()
Rectangle.area()