잡초의 일지

[Swift] Method 본문

[코딩] 배우는것/Swift

[Swift] Method

JabCho 2020. 7. 10. 20:55
728x90
반응형
SMALL

Method 

어떤 기능을 수행. 

function과는 다르게 어느 코드 블럭 안에서 동작.

 

struct extension , mutating

import UIKit

struct orderedMenu {
    var menuName: String
    var maxMenuNum: Int = 10
    var numOfOrdered: Int = 0
    
    func remainNum() -> Int {          // orderedMenu랑 관련된거니까 넣어봄.
        let remainNum = maxMenuNum - numOfOrdered
        return remainNum
    }
    
    mutating func ordered() {
        // 주문된 음식수 증가시키기
        numOfOrdered += 1            // 이 함수가 struct 안에 있는 프로퍼티 변경시키는 경우에는 mutating 써야 함.
    }
    
    static let target: String = "Anybody who want to eat this food"        // Type Property
    static func 가게이름() -> String {                // Type Method
        return "최고맛집가게"
    }
}

var food = orderedMenu(menuName: "닭강정")

func remainNum(of food: orderedMenu) -> Int {      // func를 밖에서 쓸 수도 있지만,,,
    let remainNum = food.maxMenuNum - food.numOfOrdered
    return remainNum
}


//remainNum(of: food)
food.remainNum()

food.ordered()

food.remainNum()

orderedMenu.target
orderedMenu.가게이름()

 

struct Math {
    static func abs(value: Int) -> Int {
        if value > 0{
            return value
        }else{
            return -value
        }
    }
}

Math.abs(value: -2)

extension Math {        // Math 확장하겠다! 필요한 메서드들을 또 만들 수 있음.
    static func square(value: Int) -> Int {
        return value*value
    }
    
    static func half(value: Int) -> Int {
        return value / 2
    }
}

Math.square(value: 5)
Math.half(value: 10)

var value: Int = 3              // extension으로 애플이 만들어놓은 Int라는 구조체를 바꿔 쓸 수 있다.

extension Int {
    func square() -> Int {
        return self*self
    }
    func half() -> Int {
        return self/2
    }
}

value.square()
value.half()

2020.07.11 -----------------------------------------------------------------------------------------------------------------

extension 에서 stored property는 쓸 수 없다.

computed property (연산 프로퍼티)나 method 사용할때 이용한다.

아래는 연습한거.

import UIKit

// Closure
let addClosure: (Int, Int) -> Int  = {(a:Int, b:Int) -> Int in
    return a + b
}
let subtractClosure: (Int, Int) -> Int = {(a: Int, b:Int) -> Int in
    return a-b
}
let multiplyClosure: (Int, Int) -> Int = {(a:Int, b:Int) -> Int in
    return a*b
}
let divideClosure: (Int, Int) -> Int = {(a: Int, b:Int) -> Int in
    return a/b
}

func calculateTwoNumbers(a:Int, b:Int, operation: (Int, Int) -> Int ) -> Int {
    let res = operation(a, b)
    return res
}
calculateTwoNumbers(a: 5, b: 3, operation: addClosure)
calculateTwoNumbers(a: 5, b: 3, operation: subtractClosure)
calculateTwoNumbers(a: 5, b: 3, operation: multiplyClosure)
calculateTwoNumbers(a: 5, b: 3, operation: divideClosure)

/****************************************************************************************************************************************/
// Struct
struct Lecture {
    let lectureName: String
    let teacherName: String
    var numberOfStudents: Int
    let maxStudentNum:Int = 100
}

var lec1 = Lecture(lectureName: "abc", teacherName: "ABC", numberOfStudents: 50)
var lec2 = Lecture(lectureName: "def", teacherName: "DEF", numberOfStudents: 15)
var lec3 = Lecture(lectureName: "ghi", teacherName: "GHI", numberOfStudents: 30)
var lectures = [lec1, lec2, lec3]

func findLectureName(from teacher:String, lectures:[Lecture]){
//    var name = ""
//    for lecture in lectures {
//        if teacher == lecture.teacherName{
//            name = lecture.lectureName
//        }
//    }
    
    let name = lectures.first{ (lec) -> Bool in         //for 말고 옵셔널로 표현
                            return lec.lectureName == teacher
        }?.lectureName ?? ""        //-->옵셔널로 만들어 주는 방법
    
    
    print("\(teacher)선생님의 수업 이름은 \(name) 입니다.")
}

findLectureName(from: "ABC", lectures: lectures)

/****************************************************************************************************************************************/
// extension, mutating
extension Lecture {

    mutating func register(){
        numberOfStudents += 1
    }
    
    func remainSeats()->Int {
        let remainSeats = maxStudentNum - numberOfStudents
        return remainSeats
    }
    
   static let target:String = "Anybody"
}

Lecture.target
lec1.remainSeats()
lec1.register()
lec1.register()
lec1.register()
lec1.remainSeats()

----------------------------------------------------------------------------------------------------------------------------

 

728x90
반응형
LIST
Comments