Swift/swift 문법
-
모나드Swift/swift 문법 2023. 4. 27. 18:00
: 디자인 패턴 or 자료구조, 특정 기능이 아님 - 순서가 있는 연산을 처리할 때 자주 활용하는 디자인 패턴 - 모나드는 닫힘 함수객체이다. 프로그래밍에서 모나드가 갖추어야 하는 조건 1. 타입을 인자로 받는 타입(특정 타입의 값을 포장) 2. 특정 타입의 값을 포장한 것을 반환하는 함수/ 메서드가 존재 3. 포장된 값을 변환하여 같은 형태로 포장하는 함수/메서드가 존재 예시: 옵셔널 컨텍스트 : 콘텐츠를 담은 그 무엇인가 ex) optional(2) optional() -> 컨텍스트 2 -> 콘텐츠 func addThree(_ num: Int) -> Int { return num + 3 } addThree(Optinal(2)) : 실행 불가(자료형이 달라서 실행 불가하다) Optinal(2).map(..
-
스위프트의 메모리 관리 모델Swift/swift 문법 2023. 4. 24. 19:38
값 형식과 참조 형식 값 형식 : 필요 시 항상 메모리의 값이 복사되어 전달됨 (값의 저장:stack) 값이 들어있는 스택의 스코프가 종료되면 메모리에서 자동으로 제거된다. 참조형식: 메모리의 주소를 전달 (값의 저장: Heap) -> Reference Counting을 통해 메모리를 관리 (ARC) -> 힙 영역에 할당되는 데이터는 개발자가 잘 관리해야한다. 할당이 해제되지 않으면 메모리 누수 현상이 발생. 강한참조 사이클 참조: 그 대상을 가리키고 (메모리의 주소값을 다른 인스턴스에서 저장하고 있음)있음 약한참조(weak) 예시 weak var vehicle: Car? 의미: Dog 타입의 인스턴스를 가리킬건데, RC는 올리지 않겠다. 참조하는 인스턴스가 없으면 nil을 할당할것. 비소유 참조 (un..
-
프로토콜Swift/swift 문법 2023. 4. 24. 14:44
프로토콜 이란? : 프로토콜은 특정 기능 수행에 필수적인 요수를 청의한 청사진(blueprint)입니다. 프로토콜을 만족시키는 타입을 프로토콜을 따른다(conform)고 말합니다. 프로토콜에 필수 구현을 추가하거나 추가적인 기능을 더하기 위해 프로토콜을 확장(extend)하는 것이 가능합니다. 프로토콜 -> 클래스와 상속의 단점 보완 1. 하나의 클래스만 상속 가능 2. 기본적인 상위 클래스의 메모리 구조를 따라갈 수 밖에 없음. 3. 클래스 에서만 가능 프로토콜 - 선택적 요구사항의 구현 :메서드 선언 앞에 @objc를 붙여주면 된다. 프로토콜의 확장은 클래스와 구조체가 메서드를 호출하는 방식이 다르다. [인스턴스의 타입을 해당 클래스/구조체로 인식한 경우] 클래스 -> V 테이블 구조체 -> 코드주소..
-
클래스와 구조체Swift/swift 문법 2023. 4. 22. 06:02
클래스 -> 틀 객체 -> 실제 데이터 (in swift) 클래스의 인스턴스 -> 객체 인스턴스 클래스 or 구조체를 통해서 메모리에 찍어낸 것 구조체가 클래스보다 가볍다. 대다수의 경우에는 구조체를 사용하고 상속과 같은 기능이 필요할 때는 클래스를 사용한다. 구조체 인스턴스의 데이터를 모두 스택에 저장한다. 스택: 함수가 실행될 때 사용됨 -> 함수의 실행에 따라 생기고 지워진다. 값 복사 클래스 참조형식(: 복사 시 하나의 데이터를 가리킨다) 인스턴스 데이터는 힙에 저장, 해당 힙을 가리키는 변수는 스택(메모리 주소값이 저장되어있음)에 저장 찍어낸 인스턴스를 쓰려면 이름이 필요한데 그 이름이 변수에 담겨 있고, 실제적으로 그 이름은 힙의 인스턴스를 가리키고 있는 것. [예시] var apple = A..
-
클로저 (1급 객체)Swift/swift 문법 2023. 4. 18. 19:03
: 보통은 익명 함수를 뜻함. 일반적인 함수는 named closure이다. 클로저는 익명함수지만 1급 객체 함수의 특성을 지닌다. -> 1급 객체*의 특성 : 함수를 타입으로 인식 1. 함수를 변수에 할당할 수 있음 2. 어떤 함수를 호출할 때 파라미터로서 전달할 수 있음 3. 함수에서 함수를 반환할 수 있음. 표현식 var closure : (parameter) -> return_type = {(value : type) -> return_type in //code } //ex // "Hello World"를 출력하는 익명함수 var str_closure : () -> String = { () -> String in return "Hello World" } var str_closure = {() -> ..
-
리턴형이 never 타입인 함수Swift/swift 문법 2023. 4. 16. 20:07
실행 후에 원래 실행되던 곳으로 돌아가지 않겠다. nonreturning 함수 : 제어권을 전달하지 않음 사용 예시 디버그 모드 -> 출시 전 어떻게 해서든 오류를 발생하는 것이 목적 func someError() { fatalError("앱 해킹시도 흔적 발견") } 디버깅 함수 assert() precondition() fatalError() assert() 함수 출시 모드에서는 자동으로 제거가 된다. : 실제 앱 출시 시 일부러 앱을 종료시켜야 하는 정도의 상황은 아니지만, 디버그모드에서는 검증 가능. - assert(someWrongInput > 0, "유저가 값을 잘못 입력") - assertionFailure("유저가 값을 잘못 입력") -> 조건에 관계 없이 반드시 에러를 출력함. preco..
-
강한참조 사이클 - weak vs unownedSwift/swift 문법 2023. 4. 11. 17:59
[객체 간의 강한참조 사이클 예방법] weak 과 unowned의 공통점 : 가르키는 인스턴스의 RC의 숫자를 올라가지 않게 한다. 차이점 weak : 소유자에 비해 보다 짧은 생명주기를 가진 인스턴스를 참조할 때 주로 사용 -> nil 자동 할당 O (가리키는 객체가 사라졌을 시) unowned: 소유자보다 인스턴스의 생명주기가 더 길거나 같은 경우에 사용 -> nil 자동 할당 X, error 발생 [클로저에서의 강한참조 사이클 예방법] 캡처리스트 안에서 weak or unowned 사용