옵셔널(optional)
Option type
위키 : https://en.wikipedia.org/wiki/Option_type
Option type - Wikipedia
For families of option contracts in finance, see Option style. In programming languages (especially functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.
en.wikipedia.org
Nullable type
위키 : https://en.wikipedia.org/wiki/Nullable_type
Nullable type - Wikipedia
Nullable types are a feature of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type. In statically typed languages, a nullable type is an option type[citation needed], w
en.wikipedia.org
옵셔널 타입(Option type)
값을 반환할 때 오류가 발생할 가능성이 있는 값은 옵셔널 타입이라는 객체로 감싸서 반환함
var x : Int? //nil
x = 10 //Optional(10)
var x : Int! //nil
Int("123") //Optional(123) - initializer
print(Int("Hi")) //nil
Swift에서 기본 자료형(Int, Double, String 등)은 nil값을 저장할 수 없음
nil을 저장하려면 옵셔널 타입으로 선언해야 함
옵셔널 타입은 변수 또는 상수에 아무런 값이 할당되지 않는 상황을 안전하게 처리하기 위한 방법 제공
옵셔널 타입 강제 언래핑(forced unwrapping)
var x : Int? = 10//Optional(10)
print(x!)//10
옵셔널 타입 강제 언래핑(forced unwrapping) : optional binding
옵셔널에 할당된 값을 임시 변수 또는 상수에 할당
var x : Int?
x = 10
if let xx = x //optional binding (일반상수)
{
print(x,xx)//Optional(10), 10
}
if var xx = x //optional binding (일반변수)
{
print(x,xx)//Optional(10), 10
}
옵셔널 값으로 사용하려고 하지만, optional로 사용할 수 없는 경우 Swift는 값을 강제로 풀어서 일반형처럼 사용할 수 있다. => Optional로 사용되지 않으면 자동으로 unwrap한다.
let a : Int! = 1//Optional(10)
let b : Int = a//1,optional로 사용되지 않음
let c : Int = a!//1,optional로 사용
let d = a//Optional(10),optional로 사용
let e = a + 1//2,optional로 사용되지 않음
옵셔널사용하는 이유 => 옵셔널 타입만이 값을 갖지 않는다는 의미의 nil 값을 가질 수 있음
nil => 값이 없는 상태를 의미
클래스로부터 만들어진 객체를 인스턴스라 한다.(When an object is created by a constructor of the class, the resulting object is called an instance of the class.)
형 변환(upcasting & downcasting)
업캐스팅은 자식 인스턴스를 부모 클래스로 변환하는 데 사용
as 연산자를 이용한 타입 변환
let myButton: UIButton = UIButton()
let myControl = myButton as UIControl //자식인스턴스인 myButton을 부모 클래스형으로 형 변환
다운캐스팅은 부모 인스턴스를 자식 클래스로 변환하는 데 사용
성공 확신이 있으면 as! 키워드(변환이 안되면 crash
성공 확신이 없으면 as?를 사용(변환이 안되면 nil을 리턴하므로 옵셔널 타입으로 반환함
타입 검사(is) => is 키워드를 이용하여 값의 타입 검사(type check)
ex)
if myobject is MyClass { // myobject는 MyClass의 인스턴스이다 }
class A {}
var a : A = A()
if a is A{ print("Yes") }
Any와 AnyObject
AnyObject
상속관계가 아니라도 타입 캐스팅 가능한 타입
어떤 클래스의 객체도 저장 가능
클래스만 허용하며 구조체나 열거형은 허용하지 않음
Any
클래스, 구조체, 열거형, 함수타입도 가능
연산자(operator)
x++ // x를 1 증가시킴, Swift 3에서 없어짐, x+=1
x-- // x를 1 감소시킴, Swift 3에서 없어짐, x-=1
== operator checks if their instance values are equal, "equal to"
=== operator checks if the references point the same instance, "identical to"(같은 주소를 가지고 있는가)
x...y // 닫힌 범위 연사자(closed range operator) , x에서 시작하여 y로끝나는 범위에 포함된 숫자
x..<y // 반 열린 범위 연사자(half-open range operator) , x에서 시작하여 y가 포함되지 않는 모든 숫자
2... // One-Sided Ranges 한도내의범위에서 지정된 수 부터의 숫자
ex)
let names = ["a","b","c","d","e"]
for x in names[2...]// 3번 반복
z = x ?? y//Nil-Coalescing Operator (Nil합병연산자), x의 값이 nil인경우 y의 값을 반환 nil이 아닌경우 x의 값을 반환 z는 Optional값이 아님
제어문
Swift 3에서 없어진 문법
for 초기화; 조건식; 증감식 {
// 실행될 구문
} //for x in 0..<10 로 수정시 가능
for 상수명 in 컬렉션 또는 범위 //상수명은 _로 생략 가능
{
// 실행될 코드
}
++
let numberOfLegs = ["Spider": 8, "Ant": 6, "Dog": 4]
for (animalName, legCount) in numberOfLegs
{
print("\(animalName), \(legCount)") // 1차 spider,8 2차 dog,4
}
repeat {
//
} while 조건식 // swift 1.x의 do … while 반복문을 대신하는 문
if문 // 스위프트에서는 if 문 다음의 실행 코드가 한 줄이라도 중괄호({})를 필수적으로 사용해야 한다.
if a < b, d > c// 여기서 ','는 and의 역할을함
{ print("yes") }
'잡다한지식 > iOS프로그래밍기초' 카테고리의 다른 글
iOS 학습과정(6주차) - Swift 문법 (0) | 2021.10.05 |
---|---|
iOS 학습과정(5주차) - Swift 문법 (0) | 2021.09.29 |
iOS 학습과정(4주차) - Swift 문법 (0) | 2021.09.23 |
iOS 학습과정(2주차) - 자료형 (0) | 2021.09.09 |
iOS 학습과정(1주차) (0) | 2021.09.02 |