iOS
[iOS 앱 개발] Swift 다형성(protocol, class) 예제 코드
Dokon Jang
2022. 9. 20. 15:30
반응형
Swift에서 다형성 구현한 간단하 예제입니다.
protocol과 class를 사용하여 구현된 소스입니다.
protocol Shape {
func draw()
}
class Rectangle : Shape {
var width : Int
var height : Int
init (width : Int, height : Int){
self.width = width
self.height = height
}
func draw(){
print("Width : \(width), Height : \(height)");
}
}
class Circle : Shape {
var x : Int
var y : Int
var r : Int
init (x : Int, y : Int, r : Int){
self.x = x
self.y = y
self.r = r
}
func draw(){
print("X : \(x), Y : \(y), R : \(r)");
}
}
var r = Rectangle(width : 10, height : 10)
var c = Circle(x : 0, y : 0, r : 5)
var drawList : [Shape] = []
drawList.append(r)
drawList.append(c)
for s in drawList {
s.draw()
}
반응형