처음부터 차근차근

Swift 문법 복습3 본문

프로그래밍/Swift

Swift 문법 복습3

_soyoung 2022. 3. 26. 14:07
반응형
class Man{
    var age : Int
    var weight : Double 
    func display(){
        print("나이=\(age), 몸무게=\(weight)")
        
    }
    init(age: Int  , weight : Double){  
        self.age = age
        self.weight = weight
    }
    
}

class Student : Man {//비어있지만Man의  모든 것을 가지고 있음
    
}
var kim : Man = Man(age:10, weight:20.5) 
kim.display()
var lee : Student = Student(age:20,weight:65.2)  
lee.display()
print(lee.age)
//나이=10, 몸무게=20.5
//나이=20, 몸무게=65.2
//20




class Man{
    var age   : Int
    var weight : Double
    func display(){
        print("나이=\(age)   , 몸무게=\(weight)")
            
    }
    init(){           //이렇게init()을하나라도직접 만들면 눈에 안보이는
        age = 1         //아무일도 하지 않는default init()은사라짐
        weight = 3.5
        
    }
}
var kim : Man = Man() //인스턴스가만들어지면서init() 자동 호출됨kim.display()





class Man{
    var age : Int
    var weight : Double
    func display(){
        print("나이=\(age), 몸무게=\(weight)")
    }
    init(yourAge: Int, yourWeight: Double){
        age = yourAge
        weight = yourWeight
    } //designated initializer
    
}
//var kim : Man = Man()  //오류
var kim : Man = Man(yourAge:10, yourWeight:20.5) 
kim.display()
// 나이=10, 몸무게=20.5





//과제 : 주석 달기
import UIKit
class ViewController : UIViewController{
    @IBOutletvar lblHello:UILabel! // 옵셔널 형이어서 init이나 초기화를 하지 않아도 자동으로 nil이 대입된다
    @IBOutletvar txtName: UITextField!
    //Interface Builder Outlet(변수, 프로퍼티)
    overridefuncviewDidLoad() {
        super.viewDidLoad() 
    }
    @IBAction func btnSend(_ sender: UIButton) {//Interface Builder Action(함수, 메서드)
        lblHello.text= "Hello, "+ txtName.text!
    }
}




protocol Runnable{   //대리하고싶은 함수 목록 작성
    var x: Int{ get set } //읽기와쓰기 가능 프로퍼티,{get}은읽기 전용
    //property in protocol must have explicit { get } or { get set } specifier
    func run()//메서드는선언만 있음
}
class Man : Runnable {  //채택, adopt
    var x: Int = 1 //준수, conform 
    func run() {
        print("달린다~")
    }  //준수, conform  
} 




enum Compass {
    case North
    case South
    case East
    case West
}//var x : Compass  //Compass형인스턴스x
print(Compass.North) //North
var x = Compass.West//print(type(of:x)), Compass 레포트
x = .East    //print(x), East
//North



enum Compass {
    case North
    case South
    case East
    case West
}
var direction : Compass
direction = .South
switch direction{ //switch의비교값이열거형Compass  
case .North:    //direction이.North이면"북"출력
    print("북")
case .South:
    print("남")
case .East:
    print("동")
case .West:
    print("서")  //모든열거형case를포함하면default없어도됨
}
//남




enum Week: String {
    case Mon,Tue,Wed,Thur,Fri,Sat,Sun
    func printWeek() {  //메서드도가능
        switch self {
        case .Mon, .Tue, .Wed, .Thur, .Fri:
            print("주중")
        case .Sat, .Sun:
            print("주말")    
        }
    }
}
Week.Sun.printWeek()  //레포트
//주말




enum Week: String {
    case Monday = "월"
    case Tuesday = "화"
    case Wednesday = "수"
    case Thursday = "목"
    case Friday = "금"
    case Saturday //값이지정되지않으면case 이름이할당됨
    case Sunday   // = "Sunday"
}
print(Week.Monday) //Monday
print(Week.Monday.rawValue) //월
print(Week.Sunday)
print(Week.Sunday.rawValue)
//Monday
//월
//Sunday
//Sunday




enum Date {
    case intDate(Int, Int, Int)  //(int,Int,Int)형연관값을갖는intDate
    case stringDate(String)    //String형연관값을값는stringDate
}
var todayDate = Date.intDate(2022,4,30) 
todayDate = Date.stringDate("2022년5월20일") //주석처리하면?
switch todayDate{
case .intDate(let year, let month, let day):
    print("\(year)년\(month)월\(day)일")
case .stringDate(let date):
    print(date)
}
//2022년5월20일



let age: Int? = 30 //Optional(30)
switch age {
case .none: // nil인경우
    print("나이정보가없습니다.")
case .some(let a) where a < 20:
    print("\(a)살미성년자입니다")
case .some(let a) where a < 71:
    print("\(a)살성인입니다")
default:
    print("경로우대입니다")
} 
//30살성인입니다




var x : Int? = 20  //.some(20) 
var y : Int? = Optional.some(10)
var z : Int? = Optional.none
var x1 : Optional<Int> = 30 
print(x, y, z, x1)  //레포트
//Optional(20) Optional(10) nil Optional(30)




struct Resolution {  //구조체정의
var width : Int//프로퍼티초기값이없어요!!
var height : Int
} //init()메서드가 없어도 자동으로 만들어진 Memberwise Initializer 때문에 아래와 같은 방식으로 프로퍼티를 초기화 해도 된다.
let myComputer = Resolution(width:1920,height:1080) //Memberwise Initializer 
print(myComputer.width)
//1920

class Resolution {  
    var width : Int
    var height : Int
    init(width : Int, height : Int) { // 구조체와 다른점 : class는 designated Initializer를 만들어줘야 한다.
        self.width = width
        self.height = height
    }
} 
let myComputer = Resolution(width:1920,height:1080) 
print(myComputer.width)
//1920




struct Resolution{  
    var width = 1024
    var height = 768
}
class VideoMode {   
    var resolution = Resolution()
    var frameRate = 0.0
}
let myVideo = VideoMode()
print(myVideo.resolution.width)
print(myVideo.resolution.height)
//1024
//768


// 구조체는 값타입이다.(value type)
// 값이 복사되기 때문에 kim.age의 값은 변하지 않는다.
struct Human{
    var age : Int = 1
}
var kim = Human()
var lee = kim//값타입
print(kim.age,lee.age) 
lee.age = 20
print(kim.age,lee.age)
kim.age = 30
print(kim.age, lee.age)
// 1 1
//1 20
//30 20



// class는 참조타입이다.(reference type)
// kim.age오ㅓ
class Human{
var age : Int = 1
    
}
var kim = Human()
var lee = kim//참조타입
print(kim.age, lee.age) 
lee.age = 20
print(kim.age,lee.age) 
kim.age = 30
print(kim.age, lee.age)
//1 1
//20 20
//30 30



struct Resolution {
    var width = 0
    var height = 0
}
class VideoMode{
    var resolution = Resolution()
    var frameRate = 0 
    var name: String?
}
var hd = Resolution(width: 1920, height: 1080) //자동 MemberwiseInitializer 
var highDef = hd//구조체는값타입(value type)
print(hd.width, highDef.width)
hd.width = 1024
print(hd.width, highDef.width)

var xMonitor = VideoMode()  
xMonitor.resolution = hd
xMonitor.name = "LG"
xMonitor.frameRate = 30
print(xMonitor.frameRate)  
var yMonitor = xMonitor//클래스는참조타입(reference type)
yMonitor.frameRate = 25
print(yMonitor.frameRate)  
print(xMonitor.frameRate)
//1920 1920
//1024 1920
//30
//25
//25

class ViewController:UIViewController,UIPickerViewDelegate, UIPickerViewDataSource{
UIViewController는 부모 클래스
UIPickerViewDelegate, UIPickerViewDataSource는 프로토콜



optional func pickerView(_ pickerView: UIPickerView, 
   rowHeightForComponent component: Int) -> CGFloat
앞에 optional이 붙어있는 메소드는 필수로 구현해야하는 메소드가 아니다.
필요할 때만 구현한다.

func numberOfComponents(in: UIPickerView) -> Int
앞에 optional이 붙지 않은 



// Return the number of rows for the table.     
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return 0
}
//raw의 개수를 묻는 메서드

// Provide a cell object for each row.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   // Fetch a cell of the appropriate type.
   let cell = tableView.dequeueReusableCell(withIdentifier: "cellTypeIdentifier", for: indexPath)
   
   // Configure the cell’s contents.
   cell.textLabel!.text = "Cell text"
       
   return cell
}
// 칸(cell)을 채울 내용이 뭔지 얻을 때 사용하는 메서드
// 이 두개의 메서드는 TableView를 사용할 때 반드시 구현해야하는 메서드

 

 

 

 

출처 : iOS프로그래밍실무(22-1학기)한성현교수 강의 내용 변형 및 요약

반응형

'프로그래밍 > Swift' 카테고리의 다른 글

Swift 문법 복습5  (0) 2022.04.11
Swift 문법 복습4  (0) 2022.03.29
Swift 문법 복습2  (1) 2022.03.18
Swift 문법 복습1, json 정리 사이트  (0) 2022.03.17
강의 내용 정리  (0) 2021.11.29
Comments