Toy Project/Swift Language Syntax 17

16. Swift Initializer(생성자)

목차 자식클래스가 새로운 형태로 Initializer를 만드는 방법 2-phase Initialization (클래스 생성시 2단계) 상속이 깊어지면 Initializer에 전달하는 파라미터의 갯수도 늘어난다. 규칙 code 1. 자식클래스가 새로운 형태로 Initializer를 만드는 방법 init(firstName: String, lastName: String, sports:[String]){ self.sports = sports super.init(firstName:firstName, lastName:lastName) // 여기서 Stored Property를 먼저 초기화한 다음에 상위 클래스의 생성자를 호출하는 것이 관례이다. 이유는 2에서 알려줄께 } // 이렇게 되면 해당 클래스의 생성자에 맞..

15. Swift Class Inheritance (상속)

상속의 규칙 A is B -->명제가 논리적으로 성립하면 A는 B를 상속 받을 수 있다. 자식은 한 개의 superclass만 상속받는다. 부모는 여러 자식들을 가질 수 있다. 상속의 깊이는 상관없다. override: 오버라이딩 메소드의 경우 override 키워드를 삽입한다. upper casting: 상위클래스로 casting할 때, 명시적으로 (as 클래스이름) 표시할 수 있다. athelete1 = athelete2 as StudentAthlete 여기서 upper casting가 되었기에 athelete1은 이제 footballTeam에 접근할 수 없다. down casting: 하위클래스로 casting할 때이며, 안전하게 optional하게 casting된다. 정상적으로 binding가 된..

14. Swift Class

Struct와 Class를 정의하면서 차이를 살펴보자 Structure는 property의 값 변경을 만드는 함수는 mutating 키워드를 이용해야한다. Class의 경우 할당될 때 실행되는 생성자를 선언해야 한다. Structure도 생성자 init()를 정의할 수 있다. struct PersonStruct { var firstName: String var lastName: String var fullName: String { return "\(firstName) \(lastName)" } init(firstName: String, lastName: String){ self.firstName = firstName self.lastName = lastName } mutating func uppercas..

13. Swift Method extension

이미 만든 Structure에 메소드를 추가하고 싶다. instance, type 이던 method를 추가할 수 있다. 기존의 structure에서 코드를 추가해도 되지만 현재 코드라인에서 사용하고 싶으면(이게 가독성이 좋겠다라고 생각되면) extansion을 이용해도 된다. 그리고 협업시 모든 사람들이 해당 Structure에 접근하면 오류가 커질 수 있기에 각각 추가 코드라인을 만들어서 정상적으로 디버깅되면 추가하는 것도 좋은 방법이다. struct Math { static func abs(value: Int) -> Int { if value > 0 { return value } else { return -value } } } print(Math.abs(value: -20)) // 제곱, 반값이 필요..

12. Swift Method

function과 method의 차이: method는 instance에 귀속되어서 사용할 수 있는 것 function과 마찬가지로 기능을 수행하는 코드블록이다. function과 다르게 Structure, Class안에서 동작하는 것 이번에는 Structure와 관련된 Method에 대해 알아보자 struct Lecture { var title: String var maxStudents: Int = 10 var numOfRegistered: Int = 0 // 강의의 남은 자리수 확인하는 함수 func remainSeats() -> Int { return lec.maxStudents - lec.numOfRegistered } // swift는 var 변수라도 함부로 값을 변경하면 안된다. // func ..

11. Swift Property(속성)

Property: 속성, 데이터를 의미 Stored Property: 값이 초기화되어 저장되어있는 데이터(nil로 저장된것도 포함) Computed Property: 어떤 값을 저장하지 않고 저장된 정보를 이용해서 가공 혹은 계산된 값을 이용 접근할때마다 다시 계산이 되어 값 변경시 새로운 값을 이용해서 다시 제공한다. Protocol에서의 예시인 var description이 Computed Property이다. 꿀팁을 주자면 변수가 var로 되어있는데 값변경으로인한 오류를 막기위해 let으로 선언을 권고 struct Person { var firstName: String var lastName: String var fullName: String { return "\(firstName) \(lastNa..

10. Swift Protocol

Protocol: 규약, 약속 꼭 구현되어야하는 method나 Property(속성) 같은것들이다. 즉, 어떤 서비스를 이용할 때 반드시 필요한 것들이 있을 것인데, 프로토콜을 서비스에서 반드시 필요한 일, 요소들을 의미한다. Integer 도 Structure로 구성되어 있다. public struct Int : FixedWidthInteger, SignedInteger 여기서 FixedWidthInteger, SignedInteger 이 프로토콜이라는 놈들이다. public protocol CustomStringConvertible { public var description: String {get} } 여기서 CustomStringConvertible이 protocol이라고 선언이 되면 내부에 있는..

9. Swift Structure practice

// 도전과제 // 1. 강의이름, 강사이름, 학생수를 가지는 구조체 만들기 (Lecture) // 2. 강의 array와 강사이름을 받아서, 해당 강사의 강의이름을 출력하는 함수만들기 // 3. 강의 3개를 만들고, 강사이름으로 강의찾기 struct Lecture { let lectureName: String let lectureTeacher: String let numOfStudent: Int } let lec1 = Lecture(lectureName: "OS", lectureTeacher: "김호원", numOfStudent: 40) let lec2 = Lecture(lectureName: "Database", lectureTeacher: "이기준", numOfStudent: 50) let lec3..

8. Swift Structure

// Structure: 관계가 있는 것들을 묶어서 표현한 것 // Structure와 Class는 동작이 다르다. // 구조체는 Value Types으로 변수에 할당될 때 Copy되어 할당된다. // 클래스는 Reference Types으로 변수에 할당될 때 참고되는 형태(공유)로 할당된다. // Structure는 Stack에 할당되고, Class는 Heap에 할당이 된다. // let pClass1 = PersonClass(name: "me") // let pClass2 = pClass1 // pClass2.name = "Hey" // pClass1.name // Hey // pClass2.name // Hey // let pStructure1 = PersonStruct(name: "me") // ..

7. Swift Closure 조금더

// Closure 보강!!!! // 함수는 어떤 기능을 수행하는 코드블록이며, // Swift에서는 함수와 같이 기능을 수행하는 코드블록의 특별한 타입인 Closure가 존재한다. 사실 Closure가 더 상위 개념이다 // Swift 공식사이트에서 정의한 Closure: // Closure는 크게 3가지 타입이 존재한다. // Global functions are closures that have a name and don’t capture any values. // Nested functions are closures that have a name and can capture values from their enclosing function. // Closure expressions are unna..

6. Swift Closure basic

// Closure : 이름이 없는 메소드라고 생각하면 된다. // (Int, Int) -> Int : 클루져의 타입 var multiply1: (Int, Int) -> Int = { (a:Int, b:Int) -> Int in return a * b } // 여기서 간략하게 쓸 수 있다. // a, b는 Int로 들어올 것이고, 반환도 Int로 한다고 type을 지정했다. var multiply2: (Int, Int) -> Int = { a, b in return a * b } // 그리고 들어오는 파라미터의 index를 나타낼 수 있다. var multiply3: (Int, Int) -> Int = { return $0 * $1 } var multiplyClosure: (Int, Int) -> Int..

5. Swift Collection(Dicionary, Set)

// Dictionary // 순서가 없이 key와 value로 구성된다. // 커피에 이름을 적는 것과 비슷한 구조이다. // Key는 Unique해야한다. var scoreDic: [String: Int] = ["Jason": 80, "Jay": 95, "Jake": 90] var scoreDic1: Dictionary = ["Jason": 80, "Jay": 95, "Jake": 90] print(scoreDic) print(scoreDic["Jay"]) // Optional type이다. 없을 수 있기때문 print(scoreDic["duddn"]) // nil 값이 나온다. if let score = scoreDic["Jay"] { print(score) } // isEmpty, count pr..