SlideShare une entreprise Scribd logo
1  sur  34
구조체와 클래스
BoostCamp 정승욱
구조체
struct BasicInfo {
let name : String
var age : Int
}
var johnInfo : BasicInfo = BasicInfo (name : "john", age : 18)
johnInfo.age = 19 // 변경 가능
johnInfo.name = “sam” // 변경 불가
let johnInfo : BasicInfo = BasicInfo (name : "john", age : 18)
johnInfo.age = 19 // 변경 불가
구조체 정의 구조체 인스턴스의 생성 및 초기화
구조체
struct Fahrenheit {
var temperature: Double
init() {
temperature = 32.0
}
}
struct Fahrenheit {
var temperature = 32.0
}
init() 초기화 기본값 설정
var f = Fahrenheit()
print("The default temperature is (f.temperature)° Fahrenheit")
// Prints "The default temperature is 32.0° Fahrenheit"
구조체
struct Celsius {
var temperature: Double
init (fromFahrenheit fahrenheit: Double) {
temperature = (fahrenheit - 32.0) / 1.8
}
init (fromKelvin kelvin: Double) {
temperature = kelvin - 273.15
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
초기화 매개변수
구조체
struct Color {
let red, green, blue: Double
init (red: Double, green: Double, blue: Double) {
self.red = red
self.green = green
self.blue = blue
}
init (white: Double) {
red = white
green = white
blue = white
}
}
매개변수 이름
let magenta = Color (red: 1.0, green: 0.0, blue: 1.0)
let halfGray = Color (white: 0.5)
let veryGreen = Color (0.0, 1.0, 0.0) // Error
구조체
인자 레이블 없는 초기화 매개변수
struct Celsius {
var temperature: Double
init (fromFahrenheit fahrenheit: Double) {
temperature = (fahrenheit - 32.0) / 1.8
}
init (fromKelvin kelvin: Double) {
temperature = kelvin - 273.15
}
init (_ celsius: Double) {
temperature = celsius
}
}
let bodyTemperature = Celsius(37.0)
구조체
옵셔널 프로퍼티 타입
struct SurveyQuestion {
var text: String
var response: String?
init (text: String) {
self.text = text
}
func ask() {
print(text)
}
}
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
// Prints "Do you like cheese?"
cheeseQuestion.response = "Yes, I do like cheese."
구조체
실패할 수 있는 초기화
struct Animal
{
let species: String
init?(species: String) {
if species.isEmpty {
return nil
}
self.species = species
}
}
let someCreature = Animal(species: "Giraffe")
if let giraffe = someCreature {
print("An animal was initialized with a species of (giraffe.species)")
}
let anonymousCreature = Animal(species: "")
if anonymousCreature == nil {
print("The anonymous creature could not be initialized")
}
Class
클래스 정의
class ShoppingListItem{
var name: String?
var interlaced = false
var frameRate = 0.0
var name: String?
}
var item = ShoppingListItem()
print(item.frameRate)
Class
인스턴스 생성 및 사용
class Person{
var height: Float = 0.0
var weight: Float = 0.0
}
var john: Person = Person()
john.height = 123.0 // 변경 가능
john.weight = 123.0 // 변경 가능
let jenny: Person = Person()
jenny.height = 123.0 // 변경 가능
jenny.weight = 123.0 // 변경 가능
Class
클래스 상속
class Vehicle {
var numberOfWheels = 0
var description: String {
return "(numberOfWheels) wheel(s)"
}
}
class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
let vehicle = Vehicle()
print("Vehicle: (vehicle.description)")
// Vehicle: 0 wheel(s)
let bicycle = Bicycle()
print("Bicycle: (bicycle.description)")
// Bicycle: 2 wheel(s)
식별 연산자
두 참조가 같은 인스턴스를 가리키고 있는지 검사
var john : Person = Person() // clsss Person{}
let friend : Person = john
let another : Person = Person()
print(john === friend) //?
print(john === another) //?
print(john !== another) //?
Class
클래스 인스턴스의 소멸 (Deinitialize)
let vehicle = Vehicle()
print("Vehicle: (vehicle.description)")
// Vehicle: 0 wheel(s)
let bicycle = Bicycle()
print("Bicycle: (bicycle.description)")
// Bicycle: 2 wheel(s)
class Person{
var height: Float = 0.0
var weight: Float = 0.0
deinit {
print(“Person 클래스의 인스턴스 소멸”)
}
}
Class와 Struct의 공통점
- 값을 저장하기 위해 프로퍼티 정의 가능
- 기능 수행을 위해 메서드를 정의 가능
- []를 사용해 첨자(subscript) 문법으로 내부의 값을 액세스할 수 있는 첨자를 정의 가능
- 초기 상태 설정을 위한 초기화 함수(initializer)를 정의 가능
- 클래스/구조체 구현을 확장(extension) 가능
- 특정 기능을 수행하기 위해 특정 프로토콜을 준수 가능
Class와 Struct의 차이점
- 구조체는 상속이 불가능
- 타입캐스팅은 클래스의 인스턴스에만 허용
- 디이니셜라이저는 클래스의 인스턴스에만 활용가능
- 참조 횟수 계산은 클래스의 인스턴스에만 적용
Value Type vs Reference Type
- Value Type : 인스턴스를 전달할 때 복사가 된다
- Reference Type : 주소가 전달된다
Value Type vs Reference Type
Struct Info {
let name : String
var age : Int
}
var johnInfo : Info = Info(name: “john”, age : 18)
var jennyInfo : Info = johnInfo
jennyInfo.age = 20
print(johnInfo.age) //?
Class Info {
let name : String
var age : Int
}
var johnInfo : Info = Info(name: “john”, age : 18)
var jennyInfo : Info = johnInfo
jennyInfo.age = 20
print(johnInfo.age) //?
구조체와 클래스 선택
애플의 가이드라인
( 다음 조건중 1가지 이상 해당될 때 구조체 권장 )
- 연관된 간단한 값의 집합을 캡슐화하는 것만이 목적일 때
- 캡슐화된 값이 참조되는 것보다 복사되는 것이 합당할 때
- 구조체에 저장된 프로퍼티가 값 타입이며 참조되는 것보다 복사되는 것이 합당할 때
- 다른 타입으로부터 상속받거나 자신이 상속될 필요가 없을
스위프트의 기본 데이터 타입
/* 스위프트 String 타입의 정의 */
public struct String{
public init()
}
Bool, Int, Array, Dictionary, Set 등 Struct로 구현됨
모두 Value Type
프로퍼티와 메서드
프로퍼티와 메서드
프로퍼티는 클래스, 구조체 또는 열거형 등에 관련된 값
메서드는 특정 타입에 관련된 함수를 의미
목적에 따라 용어가 조금씩 달라짐
프로퍼티
저장 프로퍼티
- 인스턴스의 변수 또는 상수를 의미 (인스턴스 변수)
- 구조체와 클래스에서만 사용할 수 있다
연산 프로퍼티
- 값을 저장한 것이 아닌 특정 연산을 수행한 결과값을 의미
- 클래스, 구조체, 열거형에서 사용할 수 있다
특정 타입의 인스턴스에서 사용
타입 프로퍼티
- 특정 타입에서 사용되는 프로퍼티 (클래스 변수)
저장 프로퍼티
클래스 또는 구조체의 인스턴스와 연관된 값을 저장
- var, let
struct CoordinatePoint {
var x : Int
var y : Int
}
let point : CoordinatePoint = CoordinatePoint(x: 10, y: 10)
//구조체는 저장 프로퍼티를 매개변수로 가지는 이니셜라이저가 존재
//클래스는 저장 프로퍼티의 기본값이 없다면 사용자정의 이니셜라이저를 구현해야함
지연 저장 프로퍼티
struct CoordinatePoint {
var x : Int = 0
var y : Int = 0
}
class Position {
lazy var point : CoordinatePoint = CoordinatePoint()
let name : String
init(name : String){
self.name = name
}
}
let position : Position = Position(name:"john")
// 아래 코드를 통해 point 프로퍼티로 처음 접근할 때 point 프로퍼티의 CoordinatePoint가 생성
print(position.point)
프로퍼티 감시자
class Account {
var credit: Int = 0 {
willSet {
print("잔액이 (credit)원에서 (newValue)원으로 변경될 예정")
}
didSet {
print("잔액이 (credit)원에서 (oldValue)원으로 변경")
}
}
}
let myAccount: Account = Account()
// 잔액이 0원에서 1000원으로 변경될 예정
myAccount.credit = 1000
//잔액이 1000원에서 0원으로 변경
연산 프로퍼티
struct CoordinatePoint {
var x : Int
var y : Int
oppositePoint : CoordinatePoint { //연산 프로퍼티
// 접근자
get {
return CoordinatePoint(x: -x, y: -y)
}
// 설정자
set (opposite) {
x = - opposite.x
y = - opposite.y
}
}
}
set {
x = -newValue.x
y = -newValue.y
}
or
프로퍼티 감시자
- 프로퍼티 값이 변경될 때마다 호출
- 일반 저장 프로퍼티에서만 사용 가능(lazy X)
- 상속된 저장 프로퍼티나 연산 프로퍼티에 적용 가능
- 연산 프로퍼티의 접근자와 설정자를 통해 프로퍼티 감시자 구현 가능
- 메서드
willSet : 변경되기 전에 호출 (newVlaue가 매개변수 이름으로 자동 지정)
didSet : 변경 후 호출 (oldVlaue가 매개변수 이름으로 자동 지정)
타입 프로퍼티
class Aclass {
// 저장 타입 프로퍼티
static var typeProperty : Int = 0
//연산 타입 프로퍼티
static var typeComputedProperty : Int {
get{
return typeProperty
}
set{
typeProperty = newValue
}
}
}
AClass.typeProperty = 123
print(AClass.typeProperty) //123
print(AClass.typeComputedProperty) //123
타입 프로퍼티
- 이전까지의 프로퍼티 개념은 인스턴스 프로퍼티
- 타입 프로퍼티는 타입 자체에 속하게 되는 프로퍼티
- 타입 자체에 영향을 미침
- 유일한 값을 나타냄
- 모든 인스턴스에서 공용으로 접근하고 값을 변경할 수 있는 변수 (static)
메서드
- 특정 타입에 관련된 함수를 뜻함
- 클래스, 구조체, 열거형 등에서 인스턴스 메서드를 정의할 수 있다
- 타입 자체와 관련된 기능을 수행하기 위해 타입 메서드를 정의할 수 있다
여기서 타입메서드는 기존 프로그래밍 언어에서의 클래스 메서드와 유사
- 구조체와 열거형이 메서드를 가질 수 있다는 것이 기존 언어와의 큰 차이
인스턴스 메서드
- 특정 타입의 인스턴스에 속한 함수
- 인스턴스 내부의 프로퍼티 값을 변경하거나 특정 연산 결과를 반환하는 기능
- 함수와 달리 특정 타입 내부에 구현, 인스턴스가 존재할 때만 사용가능
인스턴스 메서드
class LevelClass {
//현재 레벨을 저장하는 저장 프로퍼티
var level : Int = 0 {
//프로퍼티 값이 변경되면 호출되는 프로퍼티 감시자
didSet { ~ }
}
func levelUp(){
print("Level UP!")
level += 1
}
}
var LevelClassInstance : LevelClass = LevelClass()
LevelClassInstance.levelUp()
self 프로퍼티
- 모든 인스턴스는 암시적으로 생성된 self 프로퍼티를 갖는다
- 인스턴스를 더 명확히 지칭할 수 있다
class LevelClass {
var level : Int = 0
func jumpLevel(to level : Int) {
print(“Jump to (level)”)
self.level = level
}
}
struct LevelStruct {
var level : Int = 0
mutating func reset(){
print(“Reset!”)
self = LevelStruct()
}
}
타입 메서드
- 타입 자체에 호출이 가능한 메서드
- 메서드 앞에 static keyword
- 상속 후 메서드 재정의(override) 불가

Contenu connexe

Tendances

파이썬 class 및 인스턴스 생성 이해하기
파이썬 class 및 인스턴스 생성 이해하기파이썬 class 및 인스턴스 생성 이해하기
파이썬 class 및 인스턴스 생성 이해하기Yong Joon Moon
 
파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403Yong Joon Moon
 
파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기Yong Joon Moon
 
Scala self type inheritance
Scala self type inheritanceScala self type inheritance
Scala self type inheritanceYong Joon Moon
 
python data model 이해하기
python data model 이해하기python data model 이해하기
python data model 이해하기Yong Joon Moon
 
2014-15 Intermediate C++ Study #7
2014-15 Intermediate C++ Study #72014-15 Intermediate C++ Study #7
2014-15 Intermediate C++ Study #7Chris Ohk
 
Python class
Python classPython class
Python classHerren
 
파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기Yong Joon Moon
 
2014-15 Intermediate C++ Study #6
2014-15 Intermediate C++ Study #62014-15 Intermediate C++ Study #6
2014-15 Intermediate C++ Study #6Chris Ohk
 
파이썬 Special method 이해하기
파이썬 Special method 이해하기파이썬 Special method 이해하기
파이썬 Special method 이해하기Yong Joon Moon
 
Scala companion object
Scala companion objectScala companion object
Scala companion objectYong Joon Moon
 
파이썬+데이터+구조+이해하기 20160311
파이썬+데이터+구조+이해하기 20160311파이썬+데이터+구조+이해하기 20160311
파이썬+데이터+구조+이해하기 20160311Yong Joon Moon
 
Head first디자인패턴 1~13_희민_호준
Head first디자인패턴 1~13_희민_호준Head first디자인패턴 1~13_희민_호준
Head first디자인패턴 1~13_희민_호준HoJun Sung
 
파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304Yong Joon Moon
 
[Swift] Class & Structure
[Swift] Class & Structure[Swift] Class & Structure
[Swift] Class & StructureBill Kim
 

Tendances (20)

파이썬 class 및 인스턴스 생성 이해하기
파이썬 class 및 인스턴스 생성 이해하기파이썬 class 및 인스턴스 생성 이해하기
파이썬 class 및 인스턴스 생성 이해하기
 
파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403파이썬 Descriptor이해하기 20160403
파이썬 Descriptor이해하기 20160403
 
파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기파이썬 class 및 function namespace 이해하기
파이썬 class 및 function namespace 이해하기
 
Scala self type inheritance
Scala self type inheritanceScala self type inheritance
Scala self type inheritance
 
python data model 이해하기
python data model 이해하기python data model 이해하기
python data model 이해하기
 
파이썬 심화
파이썬 심화파이썬 심화
파이썬 심화
 
2014-15 Intermediate C++ Study #7
2014-15 Intermediate C++ Study #72014-15 Intermediate C++ Study #7
2014-15 Intermediate C++ Study #7
 
Python class
Python classPython class
Python class
 
파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기
 
2014-15 Intermediate C++ Study #6
2014-15 Intermediate C++ Study #62014-15 Intermediate C++ Study #6
2014-15 Intermediate C++ Study #6
 
파이썬 Special method 이해하기
파이썬 Special method 이해하기파이썬 Special method 이해하기
파이썬 Special method 이해하기
 
Scala companion object
Scala companion objectScala companion object
Scala companion object
 
Javascript
JavascriptJavascript
Javascript
 
파이썬+데이터+구조+이해하기 20160311
파이썬+데이터+구조+이해하기 20160311파이썬+데이터+구조+이해하기 20160311
파이썬+데이터+구조+이해하기 20160311
 
Head first디자인패턴 1~13_희민_호준
Head first디자인패턴 1~13_희민_호준Head first디자인패턴 1~13_희민_호준
Head first디자인패턴 1~13_희민_호준
 
Scala trait usage
Scala trait usageScala trait usage
Scala trait usage
 
Java class
Java classJava class
Java class
 
Scala implicit
Scala implicitScala implicit
Scala implicit
 
파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304파이썬+주요+용어+정리 20160304
파이썬+주요+용어+정리 20160304
 
[Swift] Class & Structure
[Swift] Class & Structure[Swift] Class & Structure
[Swift] Class & Structure
 

Similaire à Swift3 : class and struct(+property+method)

이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)
이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)
이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)MIN SEOK KOO
 
파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131Yong Joon Moon
 
Swift 0x0e 초기화
Swift 0x0e 초기화Swift 0x0e 초기화
Swift 0x0e 초기화Hyun Jin Moon
 
9 object class
9 object class9 object class
9 object class웅식 전
 
Swift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structureSwift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structureKwang Woo NAM
 
일단 시작하는 코틀린
일단 시작하는 코틀린일단 시작하는 코틀린
일단 시작하는 코틀린Park JoongSoo
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initializationEunjoo Im
 
스위프트 성능 이해하기
스위프트 성능 이해하기스위프트 성능 이해하기
스위프트 성능 이해하기Yongha Yoo
 
자바스터디 2
자바스터디 2자바스터디 2
자바스터디 2jangpd007
 
09장 객체와 클래스 (고급)
09장 객체와 클래스 (고급)09장 객체와 클래스 (고급)
09장 객체와 클래스 (고급)유석 남
 
게임프로그래밍입문 7
게임프로그래밍입문 7게임프로그래밍입문 7
게임프로그래밍입문 7Yeonah Ki
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍Young-Beom Rhee
 
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Design patterns
Design patternsDesign patterns
Design patternsdf
 
10장 문자열 클래스와 파일 클래스
10장 문자열 클래스와 파일 클래스10장 문자열 클래스와 파일 클래스
10장 문자열 클래스와 파일 클래스유석 남
 

Similaire à Swift3 : class and struct(+property+method) (20)

이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)
이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)
이것이 자바다 Chap.11 기본 API 클래스(java)(KOR)
 
파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131
 
Swift 0x0e 초기화
Swift 0x0e 초기화Swift 0x0e 초기화
Swift 0x0e 초기화
 
9 object class
9 object class9 object class
9 object class
 
Swift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structureSwift 3 Programming for iOS : class and structure
Swift 3 Programming for iOS : class and structure
 
일단 시작하는 코틀린
일단 시작하는 코틀린일단 시작하는 코틀린
일단 시작하는 코틀린
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initialization
 
스위프트 성능 이해하기
스위프트 성능 이해하기스위프트 성능 이해하기
스위프트 성능 이해하기
 
Haskell study 6
Haskell study 6Haskell study 6
Haskell study 6
 
강의자료3
강의자료3강의자료3
강의자료3
 
자바스터디 2
자바스터디 2자바스터디 2
자바스터디 2
 
09장 객체와 클래스 (고급)
09장 객체와 클래스 (고급)09장 객체와 클래스 (고급)
09장 객체와 클래스 (고급)
 
Java_05 class
Java_05 classJava_05 class
Java_05 class
 
Scala
ScalaScala
Scala
 
게임프로그래밍입문 7
게임프로그래밍입문 7게임프로그래밍입문 7
게임프로그래밍입문 7
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
 
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
(고급자바스크립트강좌 for AngularJS, React)static of class,class 범위 안에서 static 키워드로 선언하...
 
Java(1/4)
Java(1/4)Java(1/4)
Java(1/4)
 
Design patterns
Design patternsDesign patterns
Design patterns
 
10장 문자열 클래스와 파일 클래스
10장 문자열 클래스와 파일 클래스10장 문자열 클래스와 파일 클래스
10장 문자열 클래스와 파일 클래스
 

Swift3 : class and struct(+property+method)

  • 2. 구조체 struct BasicInfo { let name : String var age : Int } var johnInfo : BasicInfo = BasicInfo (name : "john", age : 18) johnInfo.age = 19 // 변경 가능 johnInfo.name = “sam” // 변경 불가 let johnInfo : BasicInfo = BasicInfo (name : "john", age : 18) johnInfo.age = 19 // 변경 불가 구조체 정의 구조체 인스턴스의 생성 및 초기화
  • 3. 구조체 struct Fahrenheit { var temperature: Double init() { temperature = 32.0 } } struct Fahrenheit { var temperature = 32.0 } init() 초기화 기본값 설정 var f = Fahrenheit() print("The default temperature is (f.temperature)° Fahrenheit") // Prints "The default temperature is 32.0° Fahrenheit"
  • 4. 구조체 struct Celsius { var temperature: Double init (fromFahrenheit fahrenheit: Double) { temperature = (fahrenheit - 32.0) / 1.8 } init (fromKelvin kelvin: Double) { temperature = kelvin - 273.15 } } let boilingPointOfWater = Celsius(fromFahrenheit: 212.0) let freezingPointOfWater = Celsius(fromKelvin: 273.15) 초기화 매개변수
  • 5. 구조체 struct Color { let red, green, blue: Double init (red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } init (white: Double) { red = white green = white blue = white } } 매개변수 이름 let magenta = Color (red: 1.0, green: 0.0, blue: 1.0) let halfGray = Color (white: 0.5) let veryGreen = Color (0.0, 1.0, 0.0) // Error
  • 6. 구조체 인자 레이블 없는 초기화 매개변수 struct Celsius { var temperature: Double init (fromFahrenheit fahrenheit: Double) { temperature = (fahrenheit - 32.0) / 1.8 } init (fromKelvin kelvin: Double) { temperature = kelvin - 273.15 } init (_ celsius: Double) { temperature = celsius } } let bodyTemperature = Celsius(37.0)
  • 7. 구조체 옵셔널 프로퍼티 타입 struct SurveyQuestion { var text: String var response: String? init (text: String) { self.text = text } func ask() { print(text) } } let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?") cheeseQuestion.ask() // Prints "Do you like cheese?" cheeseQuestion.response = "Yes, I do like cheese."
  • 8. 구조체 실패할 수 있는 초기화 struct Animal { let species: String init?(species: String) { if species.isEmpty { return nil } self.species = species } } let someCreature = Animal(species: "Giraffe") if let giraffe = someCreature { print("An animal was initialized with a species of (giraffe.species)") } let anonymousCreature = Animal(species: "") if anonymousCreature == nil { print("The anonymous creature could not be initialized") }
  • 9. Class 클래스 정의 class ShoppingListItem{ var name: String? var interlaced = false var frameRate = 0.0 var name: String? } var item = ShoppingListItem() print(item.frameRate)
  • 10. Class 인스턴스 생성 및 사용 class Person{ var height: Float = 0.0 var weight: Float = 0.0 } var john: Person = Person() john.height = 123.0 // 변경 가능 john.weight = 123.0 // 변경 가능 let jenny: Person = Person() jenny.height = 123.0 // 변경 가능 jenny.weight = 123.0 // 변경 가능
  • 11. Class 클래스 상속 class Vehicle { var numberOfWheels = 0 var description: String { return "(numberOfWheels) wheel(s)" } } class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } let vehicle = Vehicle() print("Vehicle: (vehicle.description)") // Vehicle: 0 wheel(s) let bicycle = Bicycle() print("Bicycle: (bicycle.description)") // Bicycle: 2 wheel(s)
  • 12. 식별 연산자 두 참조가 같은 인스턴스를 가리키고 있는지 검사 var john : Person = Person() // clsss Person{} let friend : Person = john let another : Person = Person() print(john === friend) //? print(john === another) //? print(john !== another) //?
  • 13. Class 클래스 인스턴스의 소멸 (Deinitialize) let vehicle = Vehicle() print("Vehicle: (vehicle.description)") // Vehicle: 0 wheel(s) let bicycle = Bicycle() print("Bicycle: (bicycle.description)") // Bicycle: 2 wheel(s) class Person{ var height: Float = 0.0 var weight: Float = 0.0 deinit { print(“Person 클래스의 인스턴스 소멸”) } }
  • 14. Class와 Struct의 공통점 - 값을 저장하기 위해 프로퍼티 정의 가능 - 기능 수행을 위해 메서드를 정의 가능 - []를 사용해 첨자(subscript) 문법으로 내부의 값을 액세스할 수 있는 첨자를 정의 가능 - 초기 상태 설정을 위한 초기화 함수(initializer)를 정의 가능 - 클래스/구조체 구현을 확장(extension) 가능 - 특정 기능을 수행하기 위해 특정 프로토콜을 준수 가능
  • 15. Class와 Struct의 차이점 - 구조체는 상속이 불가능 - 타입캐스팅은 클래스의 인스턴스에만 허용 - 디이니셜라이저는 클래스의 인스턴스에만 활용가능 - 참조 횟수 계산은 클래스의 인스턴스에만 적용
  • 16. Value Type vs Reference Type - Value Type : 인스턴스를 전달할 때 복사가 된다 - Reference Type : 주소가 전달된다
  • 17. Value Type vs Reference Type Struct Info { let name : String var age : Int } var johnInfo : Info = Info(name: “john”, age : 18) var jennyInfo : Info = johnInfo jennyInfo.age = 20 print(johnInfo.age) //? Class Info { let name : String var age : Int } var johnInfo : Info = Info(name: “john”, age : 18) var jennyInfo : Info = johnInfo jennyInfo.age = 20 print(johnInfo.age) //?
  • 18. 구조체와 클래스 선택 애플의 가이드라인 ( 다음 조건중 1가지 이상 해당될 때 구조체 권장 ) - 연관된 간단한 값의 집합을 캡슐화하는 것만이 목적일 때 - 캡슐화된 값이 참조되는 것보다 복사되는 것이 합당할 때 - 구조체에 저장된 프로퍼티가 값 타입이며 참조되는 것보다 복사되는 것이 합당할 때 - 다른 타입으로부터 상속받거나 자신이 상속될 필요가 없을
  • 19. 스위프트의 기본 데이터 타입 /* 스위프트 String 타입의 정의 */ public struct String{ public init() } Bool, Int, Array, Dictionary, Set 등 Struct로 구현됨 모두 Value Type
  • 21. 프로퍼티와 메서드 프로퍼티는 클래스, 구조체 또는 열거형 등에 관련된 값 메서드는 특정 타입에 관련된 함수를 의미 목적에 따라 용어가 조금씩 달라짐
  • 22. 프로퍼티 저장 프로퍼티 - 인스턴스의 변수 또는 상수를 의미 (인스턴스 변수) - 구조체와 클래스에서만 사용할 수 있다 연산 프로퍼티 - 값을 저장한 것이 아닌 특정 연산을 수행한 결과값을 의미 - 클래스, 구조체, 열거형에서 사용할 수 있다 특정 타입의 인스턴스에서 사용 타입 프로퍼티 - 특정 타입에서 사용되는 프로퍼티 (클래스 변수)
  • 23. 저장 프로퍼티 클래스 또는 구조체의 인스턴스와 연관된 값을 저장 - var, let struct CoordinatePoint { var x : Int var y : Int } let point : CoordinatePoint = CoordinatePoint(x: 10, y: 10) //구조체는 저장 프로퍼티를 매개변수로 가지는 이니셜라이저가 존재 //클래스는 저장 프로퍼티의 기본값이 없다면 사용자정의 이니셜라이저를 구현해야함
  • 24. 지연 저장 프로퍼티 struct CoordinatePoint { var x : Int = 0 var y : Int = 0 } class Position { lazy var point : CoordinatePoint = CoordinatePoint() let name : String init(name : String){ self.name = name } } let position : Position = Position(name:"john") // 아래 코드를 통해 point 프로퍼티로 처음 접근할 때 point 프로퍼티의 CoordinatePoint가 생성 print(position.point)
  • 25. 프로퍼티 감시자 class Account { var credit: Int = 0 { willSet { print("잔액이 (credit)원에서 (newValue)원으로 변경될 예정") } didSet { print("잔액이 (credit)원에서 (oldValue)원으로 변경") } } } let myAccount: Account = Account() // 잔액이 0원에서 1000원으로 변경될 예정 myAccount.credit = 1000 //잔액이 1000원에서 0원으로 변경
  • 26. 연산 프로퍼티 struct CoordinatePoint { var x : Int var y : Int oppositePoint : CoordinatePoint { //연산 프로퍼티 // 접근자 get { return CoordinatePoint(x: -x, y: -y) } // 설정자 set (opposite) { x = - opposite.x y = - opposite.y } } } set { x = -newValue.x y = -newValue.y } or
  • 27. 프로퍼티 감시자 - 프로퍼티 값이 변경될 때마다 호출 - 일반 저장 프로퍼티에서만 사용 가능(lazy X) - 상속된 저장 프로퍼티나 연산 프로퍼티에 적용 가능 - 연산 프로퍼티의 접근자와 설정자를 통해 프로퍼티 감시자 구현 가능 - 메서드 willSet : 변경되기 전에 호출 (newVlaue가 매개변수 이름으로 자동 지정) didSet : 변경 후 호출 (oldVlaue가 매개변수 이름으로 자동 지정)
  • 28. 타입 프로퍼티 class Aclass { // 저장 타입 프로퍼티 static var typeProperty : Int = 0 //연산 타입 프로퍼티 static var typeComputedProperty : Int { get{ return typeProperty } set{ typeProperty = newValue } } } AClass.typeProperty = 123 print(AClass.typeProperty) //123 print(AClass.typeComputedProperty) //123
  • 29. 타입 프로퍼티 - 이전까지의 프로퍼티 개념은 인스턴스 프로퍼티 - 타입 프로퍼티는 타입 자체에 속하게 되는 프로퍼티 - 타입 자체에 영향을 미침 - 유일한 값을 나타냄 - 모든 인스턴스에서 공용으로 접근하고 값을 변경할 수 있는 변수 (static)
  • 30. 메서드 - 특정 타입에 관련된 함수를 뜻함 - 클래스, 구조체, 열거형 등에서 인스턴스 메서드를 정의할 수 있다 - 타입 자체와 관련된 기능을 수행하기 위해 타입 메서드를 정의할 수 있다 여기서 타입메서드는 기존 프로그래밍 언어에서의 클래스 메서드와 유사 - 구조체와 열거형이 메서드를 가질 수 있다는 것이 기존 언어와의 큰 차이
  • 31. 인스턴스 메서드 - 특정 타입의 인스턴스에 속한 함수 - 인스턴스 내부의 프로퍼티 값을 변경하거나 특정 연산 결과를 반환하는 기능 - 함수와 달리 특정 타입 내부에 구현, 인스턴스가 존재할 때만 사용가능
  • 32. 인스턴스 메서드 class LevelClass { //현재 레벨을 저장하는 저장 프로퍼티 var level : Int = 0 { //프로퍼티 값이 변경되면 호출되는 프로퍼티 감시자 didSet { ~ } } func levelUp(){ print("Level UP!") level += 1 } } var LevelClassInstance : LevelClass = LevelClass() LevelClassInstance.levelUp()
  • 33. self 프로퍼티 - 모든 인스턴스는 암시적으로 생성된 self 프로퍼티를 갖는다 - 인스턴스를 더 명확히 지칭할 수 있다 class LevelClass { var level : Int = 0 func jumpLevel(to level : Int) { print(“Jump to (level)”) self.level = level } } struct LevelStruct { var level : Int = 0 mutating func reset(){ print(“Reset!”) self = LevelStruct() } }
  • 34. 타입 메서드 - 타입 자체에 호출이 가능한 메서드 - 메서드 앞에 static keyword - 상속 후 메서드 재정의(override) 불가

Notes de l'éditeur

  1. 구조체는 프로퍼티와 메소드의 집합 구조체는 var, let의 프로퍼티로 정의 가능 새로운 타입을 지정하는 것이기 때문에 단어앞이 대문자인 대문자 카멜케이스 프로퍼티와 메소드는 소문자 카멜케이스 멤버와이즈 이니셜라이즈를 이용하여 초기화 var 형은 변경 가능 letd은 불가
  2. init을 이용해서 초기화 매개변수 없이 초기화 가능 결과는 같지만 프로퍼티가 항상 같은 초기값을 가진다면, 초기화에서 설정하는 것보다 기본 값을 제공하는게 좋다.
  3. 초기화 매개변수를 초기화 정의에 제공할수 있다. 서로 다른 온도를 섭씨값으로 변경하기 위해 복수개의 사용자정의 초기화 가능 첫번째 초기화는 fromFahrenheit 인자 이름과 fahrenheit의 매개변수 이름으로된 초기화 매개변수 하나를 가지고 있다. 두번째 초기화는 fromKelvein 인자 이름과 kelvin 매개변수 이름으로된 초기화 매개변수 하나를 가지고 있다. 두개의 초기화 모두 해당 섭씨 값으로 단일 인자로 변환하고 temperature 프로퍼티에 값을 저장한다.
  4. 매개변수의 개수가 서로 달라도 초기화가 가능 init은 식별가능한 이름이 없기 때문에 매개변수의 이름과 타입은 특정 초기화를 식별하기 위해 중요한 역할을 한다. 매개변수와 프로퍼티가 이름이 같을땐 self.를 이용해서 초기화 강의 때는 가능했었다
  5. 이전 예시의 확장버전 사용하고 싶지않는다면 _ 언더바를 이용해 명시적으로 작성해준다 의도가 분명할때 사용하면 좋을듯
  6. 구조체가 값이 없는 프로퍼티를 갇길 원한다면 옵셔널 타입 프로퍼티 지정 nil로 초기화 새로운 인스턴스가 초기화 될때, 자동으로 nil 기본 값을 할당하며, 아직 문자열 없음을 의미한다.
  7. 클래스, 구조체, 열거형의 초기화가 실패 할 수 있다는 것을 정의 유효하지 않는 초기화 매개변수 값에 의해서 발생 성공적으로 초기화 되는 것을 막는다. 일부분으로 하나 이상의 실패 할 수 있는 초기화를 정의 한다 초기화가 실패하는 부분에 return nil을 해준다 문자열이 들어오면 초기화 성공, 빈 문자열이 들어오면 실패 인스턴스 생성할 때 확인 아래것은 nil이 아닌 공백(String)이기에 유효하지만 빈 문자열 값인 동물은 없기 때문에 어울리지 않다. 저런 제한사항을 모델링하여 안전한 초기화를 하도록 하자
  8. 구조체와 비슷 ShoppingListItem은 자동적으로 모든 프로퍼티에 기본값으로 설정된 새로운 인스턴스를 생성하는 기본 초기화 구현을 가진다 클래스는 구조체와 다르게 멤버단위 초기화를 하지 않는다. 모든 멤버를 매개변수로하는 init만을 갖는다. 안정성을 높이게 하기위함
  9. 인스턴스 생성, 초기화된 후 프로퍼티 접근하고 싶다면 인스턴스 . 구조체와 다르게 (밸류 타입) 레퍼런스 타입(참조)이므로 let으로 선언해도 프로퍼티 값 변경 가능
  10. : 로 상속 override로 재정의
  11. true , false, true
  12. 클래스의 인스턴스는 참조타입이기 때문에 더는 참조할 필요가없을 때 메모리에서 해제 댐 저번주 튜터님의 ARC와 관련 소멸 직전에 deinit 이라는 메서드 호출 Deinitialize라고 부름 인스턴스가 메모리에서 해제되기 직전에 처리할 코드를 넣어준다.
  13. 생긴것은 비슷하지만 용도는 다르다. 프로젝트 성격, 데이터의 활용용도, 특정 타입 구현할 때 선택해서 사용 위는 애플의 가이드라인
  14. 하지만 컴파일러가 판단해서 진짜 복사를 하고 나머지 경우에는 알아서 적절히 처리
  15. 인스턴스가 생성될 때 프로퍼티의 값이 필요없다면 옵셔널로 선언해줄수 있지만 값이 할당되는 것을 지연시키고 싶을 때 이걸 사용함 지연 저장 프로퍼티는 호출이 있어야 값을 초기화 함 lazy 키워드 사용 상수는 인스턴트가 생성되기 전에 초기화되어야 하기때문에 var를 사용 복잡한 클래스나 구조체를 구현할 때 사용 클래스 인스턴스의 저장 프로퍼티로 다른 클래스 인스턴스나 구조체 인스턴스가 할당되어야 할 때, 인스턴스를 초기화 하면서 저장 프로퍼티로 쓰이는 인스턴스들이 한 번에 생성하고 싶을 때 사용 -> 성능저하나 공간 낭비를 줄일 수 있다
  16. 특정 상태에 따른 값을 연산하는 프로퍼티 접근자와 설정자 구현에 좋음 굳이 메서드를 놓고 왜? 메서드를 두개 구현해야하는데 , 분산되어있는 코드 때문에 가독성이 떨어질 수 있음 프로퍼티가 메서드보다 간편하고 직관적 저장 프로퍼티처럼 사용할 수 있다. 설정자 매개변수 생략가능. 관용적으로 newValue로 대신 가능하다.
  17. - 이전까지의 프로퍼티 개념은 타입을 정의하고 그 타입의 인스턴스가 생성됐을 때 사용될 수 있는 인스턴스 프로퍼티 각각의 인스턴스가 아닌 타입 자체에 속하게 되는 프로퍼티를 타입 프로퍼티라고 한다
  18. 2. 클래스, 구조체, 열거형 등에서 각각의 인스턴스가 특정 작업을 수행하는 기능을 캡슐화하기 위해 인스턴스 메서드를 정의할 수 있다 4. 클래스, 구조체, 열거형 등에서 자유롭게 메서드 정의 가능
  19. 2. 인스턴스 내부의 프로퍼티 값을 변경하거나 특정 연산 결과를 반환하는 기능 등 인스턴스와 관련된 기능을 수행 3. 이 점이 함수와 유일한 차이점
  20. level을 수정하는 levelUp() dㅣㄴ스턴스 메서드를 가지고 있다
  21. 자바의 this와 비슷하다 스위프트는 자동으로 메서드 내부에서 선언된 지역변수를 먼저 사용하고, 그다음 메서드 매개변수, 그다음 인스턴스 프로퍼티를 찾아서 무엇을 지칭하는지 유추함 그런데 위 코드처럼 메서드 매개변수 이름이 level인데 매개변수가 아닌 인스턴스 프로퍼티인 level을 지칭하고 싶을때 self 프로퍼티를 사용 value type의 인스턴스 자체의 값을 치환할 수 있다. 클래스 인스턴스는 참조 타입이라 할당할 수 없는데. 구조체나 열거형은 self 프로퍼티를 이용하여 자신 자체를 치환할 수 있다
  22. 객체 지향 프로그래밍에서 지칭하는 클래스 메서드와 유사