안녕하세요:)
오늘은 Swift가 제공하는 범용 자료형과 오버로딩을 통해 동일한 이름을 가진 멤버를 구현하는 방법에 대해서 알아보도록 하겠습니다!
var data: Any = 1
data = 2.3
// Any로 선언하면 형식에 관계없이 모든 자료형을 저장할 수 있습니다.
data = "Str"
data = [1, 2, 3]
// AnyObject는 참조 형식만 저장할 수 있습니다.
var obj: AnyObject = NSString()
//obj = 1 에러
// 인스턴스를 사용하기 위해서는 타입 캐스팅이 필요합니다.
// Any와 AnyObject는 타입 캐스팅이 핋요합니다.
if let str = data as? String {
print(str.count)
} else if let list = data as? [Int] {
}
// Type Casting Pattern
switch data {
case let str as String:
print(str.count)
case let list as [Int]:
print(list.count)
case is Double:
print("Double Value")
default:
break
}
func process(value: Int) {
print("process Int")
}
func process(value: String) {
print("process String")
}
func process(value: String, anotherValue: String) {
}
func process(_ value: String) {
}
process(value: 0)
process(value: "str")
process("str")
func process(value: Double) -> Int {
return Int(value)
}
func process(value: Double) -> String? {
return String(value)
}
let result: Int = process(value: 12.34)
let result2: String? = process(value: 12.34)
let result3 = process(value: 12.34) as Int
//메소드, 생성자, 성브스크립트에서도 동일한 규칙이 사용됩니다.
struct Rectangle {
func area() -> Double {
return 0.0
}
static func area() -> Double {
return 0.0
}
}
let r = Rectangle()
r.area()
Rectangle.area()
함수 이름이 동일하다면 선언된 파라미터 수로 구분합니다.
함수 이름, 파라미터 수가 동일하다면 파라미터 자료형으로 구별합니다.
함수 이름, 파라미터 수와 자료형이 동일하다면 Argument Label로 구별합니다.
함수 이름, 파라미터, Argument Label이 동일하다면 리턴형으로 구별합니다.