안선생의 개발 블로그

Swift 문법(2 본문

Swift

Swift 문법(2

안선생 2021. 10. 11. 17:34

클래스

 

class Ahn{

var age : Int = 23 //stored property는 초기값이 있어야 한다.

var weight : Double = 68.8

}

 

class Ahn{

var age : Int?  //stored property는 초기값이 있어야 함, nil

var weight : Double!

}

 

메서드 정의

class Man{

var age : Int = 23

var weight : Double = 68.8

func d(){

print("나이는\(age)살이고 몸무게는\(weight)kg입니다.")

 }

}

var Ahn : Man = Man()

print(Ahn.age) // 23

Ahn.d() // 나이는23살이고 몸무게는68.8kg입니다.

 

인스턴스 만들고 메서드와 포로퍼티 접근

class Man{

var age : Int = 23

var weight : Double = 68.6

func display(){

print("나이=\(age), 몸무게=\(weight)")

 }

}

var ahn : Man = Man()

ahn.display() // 나이=23, 몸무게=68.6

print(ahn.age) // 23

 

클래스 메서드

class Man{

var age : Int = 23

var weight : Double = 68.6

func display(){

print("나이=\(age), 몸무게=\(weight)")

}

class func a(){

print("a은 클래스 메서드입니다.")

 }

static func b(){

print("b은 클래스 메서드(static)")

 }

}

var ahn : Man = Man()

ahn.display() // 나이=23, 몸무게=68.6

Man.a() // a은 클래스 메서드입니다.

Man.b() // b은 클래스 메서드(static)

 

인스턴스 초기화하기 : init()

class Man{

 var age : Int = 1 //초기값은 없어도 된다.

 var weight : Double = 3.5 //초기값은 없어도 된다.!!

 func display(){

  print("나이=\(age), 몸무게=\(weight)")

}

init(yourAge: Int, yourWeight : Double){

   age = yourAge

   weight = yourWeight

 } //designated initializer

}

//var kim : Man = Man() //오류

//init()을 하나라도 직접 만들면 default initializer는 사라짐

var ahn : Man = Man(yourAge:23, yourWeight:68.5)

ahn.display() // 나이=23, 몸무게=68.5

 

self

현재 클래스 내 메서드나 프로퍼티를 가리킬 때 메서드나 프로퍼티 앞에 self.을 붙입니다.

class Man{

var tall : Int = 178

var weight : Double = 68.5

func display(){

print("키는=\(tall), 몸무게=\(weight)")

}

init(tall: Int, weight : Double){

self.tall = tall //프로퍼티 = 매개변수

self.weight = weight

}

}

var ahn : Man = Man(tall:178, weight:68.5)

ahn.display() // 키는=178, 몸무게=68.5

 

stored property와 computed property

class Man{

var age : Int = 23 // stored property

var weight : Double = 68.5 // stored property

var tall : Int = 178

var manAge : Int{ //메서드 같지만 computed property임

 get{

  return age-1

 }

}

func display(){

 print("나이=\(age), 키는=\(tall) 몸무게=\(weight)")

}

init(age: Int, tall: Int, weight : Double){

  self.age = age

  self.weight = weight

  self.tall = tall

 }

}

var ahn : Man = Man(age:23, tall:178,weight:68.5)

ahn.display() // 나이=23, 키는=178 몸무게=68.5

print("만으로\(ahn.manAge)살") // 만으로22살

 

computed property의 getter

setter가 없으면 get{ }는 생략할 수 있으며 변경하지 않더라도 var로 선언해야 함

class Man{

var age : Int = 23 // stored property

var weight : Double = 68.5 // stored property

var tall : Int = 178

var manAge : Int{ //메서드 같지만 computed property임

  //get{

  return age-1

  // }

}

func display(){

 print("나이=\(age), 키는=\(tall) 몸무게=\(weight)")

}

init(age: Int, tall: Int, weight : Double){

  self.age = age

  self.weight = weight

  self.tall = tall

 }

}

var ahn : Man = Man(age:23, tall:178,weight:68.5)

ahn.display() // 나이=23, 키는=178 몸무게=68.5

print("만으로\(ahn.manAge)살") // 만으로22살

 

computed property의 setter

setter가 있으면 get{ }는 생략할 수 없음

class Man{

 var age : Int = 23 // stored property

 var weight : Double = 68.5 // stored property

 var tall : Int = 178

var manAge : Int{ //메서드 같지만 computed property임

 get{

 return age-1

 }

set(USAAge){

age = USAAge + 1

}

}

func display(){

print("나이=\(age), 키는=\(tall) 몸무게=\(weight)")

}

init(age: Int, tall: Int, weight : Double){

self.age = age

self.weight = weight

self.tall = tall

}

}

var ahn : Man = Man(age:23, tall:178,weight:68.5)

ahn.display() // 나이=23, 키는=178 몸무게=68.5

print("만으로\(ahn.manAge)살") // 만으로 22살 //getter호출

print(ahn.age) //23

ahn.manAge = 2 //setter호출

print(ahn.age) //3

 

computed property의 getter와 setter

class Man{

var age : Int = 23 // stored property

var weight : Double = 68.5 // stored property

var tall : Int = 178

var manAge : Int{ //메서드 같지만 computed property임

get{ return age-1}

set{age = newValue + 1}

}

func display(){

print("나이=\(age), 키는=\(tall) 몸무게=\(weight)")

}

init(age: Int, tall: Int, weight : Double){

self.age = age

self.weight = weight

self.tall = tall

}

}

var ahn : Man = Man(age:23, tall:178,weight:68.5)

ahn.display() // 나이=23, 키는=178 몸무게=68.5

print("만으로\(ahn.manAge)살") // 만으로 22살

print(ahn.age) //23

ahn.manAge = 2

print(ahn.age) //3

 

method overloading : 생성자 중첩

class Man{

var age : Int = 1

var weight : Double = 1

var tall : Int = 1

func display(){

print("나이=\(age), 키는=\(tall) 몸무게=\(weight)")

}

init(age: Int, tall: Int, weight : Double){//1

self.age = age

self.weight = weight

self.tall = tall

}

init(age: Int, weight : Double){//2

self.age = age

self.weight = weight

}

}

var ahn : Man = Man(age:23, tall:178,weight:68.5)//1

var ahn1 : Man = Man(age:23,weight:68.5)//2

//var kim2 : Man = Man()

//init가 없다면 인스턴스 만드는 방법

ahn.display() // 나이=23, 키는=178 몸무게=68.5

ahn1.display() // 나이=23, 키는=1 몸무게=68.5

 

failable initializer가 있는 클래스의 인스턴스 생성

class Animal{

var age : Int

var weight : Double

func display(){

print("나이=\(age), 몸무게=\(weight)")

}

init?(age: Int, weight : Double){

if age <= 0 || weight <= 0 {

return nil

}

else {

self.age = age

}

self.weight = weight

}

}

var tiger : Animal? = Animal(age:1, weight:3.5)

//1-1.옵셔널 형으로 선언

if let tiger1 = tiger { //1-2.옵셔널 바인딩

tiger1.display()

}

//2.인스턴스 생성과 동시에 옵셔널 바인딩

if let tiger2 = Animal(age:2, weight:5.5) {

tiger2.display()

}

//3.인스턴스 생성하면서 바로 강제 언래핑

var tiger3 : Animal = Animal(age:3, weight:7.5)!

tiger3.display()

//4.옵셔널 인스턴스를 사용시 강제 언래핑

var tiger4 : Animal? = Animal(age:4, weight:10.5)

tiger4!.display()

 

failable initialize가 nil반환

class Animal{

var age : Int

var weight : Double

func display(){

print("나이=\(age), 몸무게=\(weight)")

}

init?(age: Int, weight : Double){

if age <= 0 || weight <= 0 {

return nil

}

else {

self.age = age

}

self.weight = weight

}

}

var tiger : Animal? = Animal(age:-1, weight:3.5)

//옵셔널 형으로 선언

if let tiger1 = tiger { //옵셔널 바인딩

tiger1.display()

}

//인스턴스 생성과 동시에 옵셔널 바인딩

if let tiger2 = Animal(age:1, weight:5.5) {

tiger2.display() // 나이=1, 몸무게=5.5

}

var tiger3 : Animal = Animal(age:0, weight:7.5)!

tiger3.display() //crash!!

//인스턴스 생성하면서 바로 강제 언래핑

//강제 언래핑하는 방법은 위험함

 

UIColor클래스의 init()메서드 overloading, failable initializer

Overloading은 그림과 같이 구현이 다른 동일한 이름의 여러 함수를 만드는 기능입니다.

Failable initilizer은 아래 사진과 같이 init“?”가 붙어있는 것이다. 리턴값이 옵셔

널로 나오기 때문에 사용하라면 위에 예제처럼 옵셔널 바인딩을 써서 풀어줘야한

. 또는 마지막에 “!"로 붙여 강제 언래핑을 해도 되지만 crash 오류가 발생할 수

있으므로 위험하다.

UIColor클래스의 인스턴스 예

let myColor : UIColor =(hue:1, saturation: 2, brighteness: 3, alpha: 4)

let c = UIColor(displayP3Red: 1, green: 2, blue: 3, alpha: 4)

 

클래스 상속

상속 : 부모가 가진 것을 물려 받는것

class Animal{

var age : Int = 1

var weight : Double = 3.5

func display(){

print("나이=\(age), 몸무게=\(weight)")

}

init(age: Int, weight : Double){

self.age = age

self.weight = weight

}

}

class Student : Animal {

//비어있지만 Animal의 모든 것을 가지고 있음

}

var tiger : Animal = Animal(age:10, weight:20.5)

tiger.display() // 나이=10, 몸무게=20.5

var lion : Student = Student(age:20,weight:65.2)

lion.display() // 나이=20, 몸무게=65.25

print(lion.age) // 20

 

super : 부모 메서드 호출 시 사용

class Animal{

var age : Int = 1

var weight : Double = 3.5

func display(){

print("나이=\(age), 몸무게=\(weight)")

}

init(age: Int, weight : Double){

self.age = age

self.weight = weight

}

}

class Student : Animal {

var name : String

func displayS() {

print("이름=\(name), 나이=\(age), 몸무게=\(weight)")

}

init(age: Int, weight : Double, name : String){

self.name = name

super.init(age:age, weight:weight) //이 줄을 안쓰면 에러발생

}//error:'super.init' isn't called on all paths before returning from initializer

}

var lion : Student = Student(age:20,weight:65.2,name:"사자")

lion.displayS() // 이름=사자, 나이=20, 몸무게=65.2

lion.display() // 나이=20, 몸무게=65.2

 

override : 부모와 자식에 같은 메서드가 있으면 자식 우선

class Animal{

var age : Int = 1

var weight : Double = 3.5

func display(){

print("나이=\(age), 몸무게=\(weight)")

}

init(age: Int, weight : Double){

self.age = age

self.weight = weight

}

}

class Student : Animal {

var name : String = "동물"

override func display() {

print("이름=\(name), 나이=\(age), 몸무게=\(weight)")

}

init(age: Int, weight : Double, name : String){

super.init(age:age, weight:weight)

self.name = name

}

}

var dragon : Student = Student(age:200,weight:650.2,name:"용")

dragon.display() // 이름=용, 나이=200, 몸무게=650.2

 

출처 : 'iOS프로그래밍기초(21-2학기)한성현교수 강의 내용 변형 및 요약'

'Swift' 카테고리의 다른 글

간단한 iOS앱개발(2)  (0) 2021.11.16
간단한 iOS 앱 개발하기  (0) 2021.11.05
윈도우 맥 차이점  (0) 2021.11.01
Swift문법 3  (0) 2021.10.17
Swift문법  (0) 2021.10.03