print
와 같은 console.log
기능.
그러나 더 자세한 정보를 표시해줌.
데이터 타입의 하나로, Unsigned Int
Int
로 선언한 변수를 할당하려고 하면 error
Any
: 어떤 타입이든 수용 가능, 단 nil
은 불가능AnyObject
: 모든 클래스 타입 수용 가능, 단 nil
은 불가능func greeting(friend: String, me: String) {
print("Hello \(friend)! I'm \(me)")
}
// 다른 함수로 인식
func greeting(to friend: String, from me: String) {
print("Hello \(friend)! I'm \(me)")
}
// 함수를 호출할 때는 전달인자 레이블을 사용해야 한다.
greeting(to: "john", from: "mike")
// 전달 받을 값의 개수를 알기 어려울 때 가변 매개변수 사용
// 함수당 하나만 가능
func sayHello(me: String, friends: String...) -> String {
return "Hello \(friends)! I'm \(me)!"
}
print(sayHello(me: "yagom", friends: "hana", "eric", "wing"))
// Hello ["hana", "eric", "wing"]! I'm yagom!
print(sayHello(me: "yagom"))
// Hello []! I'm yagom!
optional은 기본적으로 아래와 같은 enum 형태로 되어 있다.
enum Optional<T> {
case none // 값이 설정되지 않은 경우
case some(<T>) // 값을 가지고 있는 경우
}
이 optional value를 unwrapping하는 데에는 다음과 같은 방법들이 있다.
var optionalValue: Int? = 100
// if-let을 이용한 unwrapping
func printInteger(_ integer: Int) {
print(integer)
}
if let integer: Int = optionalValue {
printInteger(integer)
} else {
print("optionalValue == nil")
}
// switch를 이용한 unwrapping
switch optionalValue {
case .none:
print("this value is nil")
case .some(let value):
print("Value is \(value)")
}
// !를 이용한 unwrapping (강제 추출)
// nil 값일 경우 오류 발생
print(optionalValue!)
다음과 같이 optional value를 선언할 수도 있다.
// 암시적 추출 optional
var optionalValue: Int! = 100
// 기존 변수처럼 사용 가능
optionalValue = optionalValue + 100