iOS/Swift
-
[Swift] 익스텐션(extension)iOS/Swift 2022. 9. 3. 17:41
익스텐션이란? 타입을 나눠서 작성하고, 하나의 타입으로 동작하는 것 기존에 작성된 타입이나 남이 작성한 타입을 확장할 수 있다 서로 다른 파일에 작성 가능하다 class Dog { func eat() { print("밥먹기") } } // 확장 extension Dog { func growl() { print("으르렁") } } var myDog = Dog() myDog.eat() // 원래 클래의 메서드 myDog.bike() // 확장한 클래스의 메서드 익스텐션으로 가능한 것 계산 프로퍼티, 메서드, 프로토콜, 서브스크립트, 중첩 타입, ... 불가능한 것 designated initializer, 저장 프로퍼티 extension과 프로퍼티 - 계산 프로퍼티 가능 (designated initiali..
-
[Swift] 객체 지향 프로그래밍iOS/Swift 2022. 9. 1. 23:55
객체 지향 프로그래밍 [예시] - 학사 관리 시스템 학생의 이름, 전공 수강신청 과목 수강신청 하기 - 게임 캐릭터 캐릭터의 능력 캐릭터 이동, 공격, 방어 등 객체 지향 프로그래밍 작성 방법 [객체의 속성] 가로, 세로 길이가 10, 20인 사각형 사각형은 객체이고, 가로 세로 길이는 사각형 객체가 가진 속성이다 [객체의 행위] 사각형의 넓이 계산 사각형은 정사각형인지 판단 사각형을 다루는 애플리케이션 클래스 객체의 타입 정의 프로퍼티 객체의 속성 정의 메소드 객체의 행위 정의 클래스에서 객체 생성 객체 생성 객체에 속성 설정 객체 메소드 실행 클래스 정의와 객체 생성 클래스 정의 class Rectangle { } 객체 생성 var rect = Rectangle() // var: 새로운 객체 대입 가..
-
[Swift] 프로토콜(protocol)iOS/Swift 2022. 8. 31. 23:57
💡 프로토콜 - 특정 역할을 하기 위한 메서드, 프로퍼티 등의 청사진이다(채택받는 타입이 구현을 약속한다) - 프로토콜은 구현부 {}가 없기 때문에 단독으로 사용이 불가하다 -> 클래스, 구조체와 함께 사용 - 프로토콜을 사용하면 클래스, 구조체 등 다른 타입이더라도 같은 인터페이스로 다양한 구현이 가능하다! 프로토콜 정의 protocol 프로토콜 이름 { 프로토콜 정의 } 프로토콜 채택 // 구조체, 클래스, 열거형에서의 구현 방법 struct SomeStruct: AProtocol, AnotherProtocol { // 구조체 정의 } class SomeClass: AProtocol, AnotherProtocol { // 클래스 정의 } enum SomeEnum: AProtocol, AnotherPr..
-
[Swift] 타입캐스팅(type casting)iOS/Swift 2022. 8. 24. 23:53
💡 스위프트의 타입 캐스팅은 C++과 다르다는 걸 이해하고 넘어가자!!! 이걸 모르고 공부하면 헷갈린다 C++의 형변환(타입 캐스팅) - 묵시적 형변환 컴파일 할 때 자동으로 형변환 된다. float a = 3.14; int b; b = a; // 3 - 명시적 형변환 개발자가 직접 타입을 명시해준다. float a = 3.14; int b; b = (int)a; // 3 Swift의 형변환(이니셜라이저) var a: Double = 3.14 var b: Int = Int(a) print(b) // 3 Swift는 기존 값(a)을 전달인자로 받는 이니셔라이저를 통해 새로운 인스턴스를 생성한다. 💡 스위프트의 타입 캐스팅 인스턴스의 타입 확인 자신을 다른 타입의 인스턴스인양 행세하기 1️⃣ 인스턴스의 타입..
-
[Swift] 상속 (Inheritance)iOS/Swift 2022. 8. 22. 23:08
💡 클래스는 메서드나 프로퍼티 등을 다른 클래스로부터 상속받을 수 있다! 자식 클래스: 상속받은 클래스 부모 클래스: 자식에게 특성을 물려준 클래스 기반 클래스: 다른 클래스로부터 상속을 받지 않은 클래스 클래스 상속 시 부모 클래스의 프로퍼티, 메서드 등을 재정의하거나, 자신의 기능을 추가할 수 있다 재정의(override) 부모 클래스로부터 물려받은 특성을 그대로 사용하지 않고 변경하여 사용하는 것 ⭐️ 새로운 정의 앞에 override 키워드 사용 Q. 재정의를 하고 난 뒤에 부모 클래스의 특성을 사용하고 싶다면? ⭐️ super 키워드 1️⃣ 프로퍼티 재정의 - 프로퍼티를 재정의하는 것은 프로퍼티 자체가 아니라, 프로퍼티의 접근자, 설정자, 감시자 등을 재정의하는 것이다 - 부모 클래스에서 읽기 ..
-
[Swift] 서브스크립트(subscript)iOS/Swift 2022. 8. 20. 23:45
서브스크립트 클래스, 구조체, 열거형 등의 타입의 요소에 접근하는 문법이다 별도의 설정자(setter)와 접근자(getter) 메서드를 구현하지 않아도 인덱스를 통해 값을 설정하거나 가져올 수 있다 서브스크립트 중복정의: 여러 개 구현 O -> 값의 타입을 유추해서 적잘한 서브스크립트를 선택하여 실행한다 매개변수의 타입과 반환 타입에 제한이 없다 ⭐️ subscript 키워드 - 읽고 쓰기 - 읽기 전용 서브스크립트 정의 문법 // 읽고 쓰기 subscript(index: Int) -> Int { get { } set(newValue) { } } // 읽기 전용 subscript(index: Int) -> Int { } 예시 코드 // School 클래스 서브스크립트 구현 struct Student { ..
-
[Swift] 모나드(Monad)iOS/Swift 2022. 8. 15. 15:45
모나드 값을 어딘가에 포장하는 개념에 대한 이해에서 출발한다 함수객체(Functor)와 모나드(Monad)는 특정 기능이 아닌 디자인 패턴 혹은 자료구조라고 할 수 있다 모나드가 갖춰야하는 조건 3가지 타입을 인자로 받는 타입 특정 타입의 값을 포장한 것을 반환하는 함수가 존재 포장된 값을 변환하여 같은 형태로 포장하는 함수가 존재 모나드의 대표적인 예시: 🔥 옵셔널 - 값이 있을지 없을지 모르는 상태를 박스에 담아두는 것 옵셔널은 (1) Wrapped 타입을 인자로 받는 제네릭 타입이다 (2) Optional, init(2) 처럼 다른 타입의 값을 갖는 상태의 컨텍스트를 생성할 수 있다 (3) 옵셔널은 컨테이너와 값을 갖기 때문에 맵 함수를 사용할 수 있다 모나드를 이해하기 위해 필요한 개념 1. 컨텍..
-
[Swift] 맵, 필터, 리듀스(map, filter, reduce)iOS/Swift 2022. 8. 15. 14:57
고차 함수 매개변수로 함수를 갖는 함수이며, 맵, 필터, 리듀스는 고차함수의 일종이다. 맵(map) - 컨테이너 내부의 기존 데이터를 변형해서 새로운 컨테이너를 생성한다(컨테이너에 포장해서 반환) - for-in 반복문과 비슷하게 사용할 수 있지만 성능에서 차이가 존재한다 // MARK: map // 컨테이너 내부의 기존 데이터를 변형해서 새로운 컨테이너 생성(컨테이너에 포장해서 반환) // ex) // 배열 생성 let numbers: [Int] = [0, 1, 2, 3, 4] var doubleNumbers: [Int] var strings: [String] // MARK: for-in 구문 사용 doubleNumbers = [Int]() strings = [String]() for number in..