| 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 | 
| 12 | 13 | 14 | 15 | 16 | 17 | 18 | 
| 19 | 20 | 21 | 22 | 23 | 24 | 25 | 
| 26 | 27 | 28 | 29 | 30 | 31 | 
													Tags
													
											
												
												- 최솟값 만들기
- 프로그래머스
- 머신러닝
- 스위프트
- 카카오 2019
- 데이터셋 만들기
- Siwft
- swift 배열
- 프로그래머스 답
- swift 시작
- 카카오 2018
- swift
- ios 개발 시작
- Kakao
- 이미지학습
- c언어
- 파이썬
- 카카오
- kakao 2018
- 문제
- SwiftUI
- 카카오 2020
- 카카오 2021
- 소수
- coco 데이터셋
- fast.ai
- supervisely
- 날씨 앱
- Python
- roboflow
													Archives
													
											
												
												- Today
- Total
잡초의 일지
[Swift] Method 본문
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
    '[코딩] 배우는것 > Swift' 카테고리의 다른 글
| [Swift] Generics 제네릭 (0) | 2020.07.14 | 
|---|---|
| [Swift] Object | Class | Data , Property , Method (0) | 2020.07.13 | 
| [Swift] Object | Structure | Data , Property , Method (0) | 2020.07.10 | 
| [Swift] Protocol 프로토콜 (0) | 2020.07.10 | 
| [Swift] Structure 구조체 (0) | 2020.07.10 | 
			  Comments
			
		
	
               
           
					
					
					
					
					
					
				