본문 바로가기
Smart Device/Swift

Swift Objects and Classes #3

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

-

Class에서의 Method는 함수와는 다른 중요한 차이가 하나 있다. 함수에서 인자는 함수 내에서만

사용되지만 Class의 Method는 첫번째 인자를 제외하고는 Method를 호출할 때에도 별도의 이름을

지정해 사용될 수 있다. Method안에서 사용되어지는 두번째 인자명을 지정할 수도 있다.


class Counter {

    var count: Int = 0

    func incrementBy(amount: Int, numberOfTimes times: Int) {

        count += amount * times

    }

}

var counter = Counter()

counter.incrementBy(2, numberOfTimes: 7)


optional values을 사용할 때에는 methods, properties, and subscripting 같은 연산자 앞에 ?키워드를

사용한다. 키워드 ? 전에 값이 nil이면 ? 이후의 값도 nil이 된다.

다른 경우에 optional value는 언랩(unwrapped)되고, 키워드 ? 이후의 모든 것들은 unwrapped value

상에서 실행된다. 이 두 경우 모두 전체 표현식값에 대해 optional value가 된다.


let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")

let sideLength = optionalSquare?.sideLength


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

Swift struct  (2) 2014.07.02
Swift Enumerations  (0) 2014.06.29
Swift Objects and Classes #2 - Properties getter setter  (0) 2014.06.24
Swift Numeric Types  (0) 2014.06.12
Swift Dictionary  (0) 2014.06.12