Object는 Data와 Method로 이루어짐
Property
1. Stored Property(저장 프로퍼티)
- 값을 저장해서 변수로 사용
- didSet 사용 가능
2. Computed Property(연산 프로퍼티)
- 값을 직접 저장하지 않고 저장된 정보를 이용해서 가공 혹은 계산된 값을 제공할 때 사용
- get과 set을 이용해서 CompuedProperty에도 값을 세팅할 수 있음
Setter가 필요하면 Computed Property 그렇지 않고
계산이 많이 필요하면 Method
많이 필요하지 않으면 Computed Property
3. Type Property
- 생성된 인스턴스와 상관없이 Struct 타입 혹은 Class 타입 자체의 속성을 정하고 싶을 때 사용
- static 사용
4. Lazy Property
- 해당 프로퍼티에 접근될 때 코드가 실행되는 프로퍼티
struct Store {
// 데이터 / 프로퍼티 / Stored Property
let loc: Location
let name: String
let deliveryRange = 2.0
// 메소드
func isDeliverable(userLoc: Location) -> Bool {
let distanceToStore = distance(current: userLoc, target: loc)
return distanceToStore < deliveryRange
}
}
struct Lecture: CustomStringConvertible {
// Computed Property
var description: String {
// 원하는 lec을 입력하면 해당 강의 이름과 강사 명 출력
return "Title: \(name), Instructor: \(Instructor)" }
let name: String
let Instructor: String
let Student: Int
}
struct Person {
// Stored Property
var firstName: String {
// willSet {
// print("will set: \(firstName) --> \(newValue)")
// }
// 초기 값에서 변경된 값을 알고 싶을 때
didSet {
print("did set: \(oldValue) --> \(firstName)")
}
}
var lastName: String
lazy var isPopular: Bool = {
if fullname == "khon" {
return true
} else {
return false
}
}()
// Computed Property
var fullname: String {
get {
return "\(firstName)\(lastName)"
}
set {
// newVlaue = "khon 01"
// khon 01에서 빈 공간을 기준으로 first는 khon, last는 01이 됨
if let firstName = newValue.components(separatedBy: " ").first {
self.firstName = firstName
}
if let lastName = newValue.components(separatedBy: " ").last {
self.lastName = lastName
}
}
}
static let isAlien: Bool = false
}
// Type Property
var person = Person(firstName: "kh", lastName: "on")
person.firstName
person.lastName
// var로 설정해서 바꿀수 있음, let이면 변경 불가
person.firstName = "on"
person.lastName = "kh"
person.firstName
person.lastName
person.fullname
person.fullname = "khon 01"
person.firstName
person.lastName
Person.isAlien
person.isPopular
Method
import UIKit
struct Lecture {
var title: String
var maxStudents: Int = 10
var numOfRegister: Int = 0
// Method
func remainSeats() -> Int {
let remainSeats = maxStudents - numOfRegister
return remainSeats
}
// struct안에 메서드가 Stored property를 변경 시킬 경우 mutating을 써줘야 함
mutating func register() {
// 등록된 학생 수 증가
numOfRegister += 1
}
// type property
static let target: String = "모든 학생"
// type method
static func 학원이름() -> String {
return "Abc"
}
}
var lec = Lecture(title: "ios")
lec.remainSeats()
lec.register()
lec.remainSeats()
Lecture.target
Lecture.학원이름()
// extention
struct math {
static func abs(value: Int) -> Int {
if value > 0 {
return value
} else {
return -value
}
}
}
math.abs(value: -20)
// 확장
// 제곱과 반 값 메서드 추가
extension math {
static func square(value: Int) -> Int {
return value * value
}
static func half(value: Int) -> Int {
return value/2
}
}
math.square(value: 10)
math.half(value: 20)
var value: Int = 3
extension Int {
func square() -> Int {
return self * self
}
func half() -> Int {
return self/2
}
}
value.square()
value.half()
'Swift > 문법' 카테고리의 다른 글
lazy (0) | 2021.04.01 |
---|---|
Class / 상속 / 생성자 (0) | 2021.03.03 |
Closure (0) | 2021.03.03 |
Structure / Protocol (0) | 2021.03.02 |
Array / Dictionary / Set (0) | 2021.03.01 |