본문 바로가기
Smart Device/Swift

Swift Objects and Classes #1

by 언덕너머에 2014. 6. 9.

- Classes

  클래스에서의 속성선언은 클래스 구문안에 존재하는 것을 제외하고는 상수나 변수 선언과 동일하다.

  예)

  class Shape {

      var numberOfSides = 0

      func simpleDescription() -> String {

          return "A shape with \(numberOfSides) sides."

      }

  }


  var shape = Shape()  //()로 Class의 Instance를 생성할 수 있다.

  shape.numberOfSides = 7  // 속성에 접근하기 위해 '.'를 사용하면 된다.

  var shapeDescription = shape.simpleDescription() // methods에 접근하기 위해 '.'를 사용한다.


  Function이나 Method 선언도 속성선언과 유사하다. 그리고 Class의 initializer는 Instance가 생성될

  때 init를 사용하면 된다.

  예)

  class NameShape {

    var numberOfSides = 0

    var name: String


    init(name: String) {

      self.name = name

    }


    func simpleDescription() -> String {

      return "A shape with \(numberOfSides) sides."

    }

  }

  위 구문에서 initializer의 self.name은 속성name과 구별된다.


  모든 속성의 값은 할당되어야 하는데 numberOfSides와 같이 선언과 동시에 할당되던지 name과 같이

  initializer에 의해서 초기화되어야 한다.


- SubClass

  SubClass는 Class명 뒤에 ':'으로 구별되는 SuperClass를 포함한다.

예)

class Square: NamedShape {

    var sideLength: Double

    

    init(sideLength: Double, name: String) {

        self.sideLength = sideLength

        super.init(name: name)

        numberOfSides = 4

    }

    

    func area() ->  Double {

        return sideLength * sideLength

    }

    

    override func simpleDescription() -> String {

        return "A square with sides of length \(sideLength)."

    }

}

let test = Square(sideLength: 5.2, name: "my test square")

test.area()

test.simpleDescription()



'Smart Device > Swift' 카테고리의 다른 글

Swift Subscript  (0) 2014.06.11
Swift 연산자  (0) 2014.06.10
Swift 함수 #5 closure expression  (0) 2014.06.09
Swift 함수 #4 - 반환값과 인수의 기능을 하는 함수  (0) 2014.06.09
Swift 함수 #3 - nested functions(중첩함수)  (0) 2014.06.09