반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

swift 함수 사용 예제

2015. 8. 25. 13:46 | Posted by 솔웅


반응형


요즘 유튜브에서 Swift 관련 강좌 들으면서 공부하고 있거든.

따라 하다가 이해가 안 가서 보고 또 보고 했던 부분 정리해 두려고....

한참만에 이해 했네...


강좌는 Stanford - Developing iOS 8 Apps with Swift


import UIKit

class ViewController: UIViewController {
  @IBOutlet weak var nums: UILabel!
  var conditionA = false


  @IBAction func CalNums(sender: AnyObject) {
    let typed = sender.currentTitle!
    if conditionA {
      nums.text = nums.text! + typed!
    } else {
      nums.text = typed
      conditionA = true
    }
  }

  var operandStack = Array<Double>()


  @IBAction func enter() {
    conditionA = false
    operandStack.append(numsValue)
    println("operandStack = \(operandStack)")
  }
 
  var numsValue: Double{
    get {
      return NSNumberFormatter().numberFromString(nums.text!)!.doubleValue
    }
    set {
      nums.text = "\(newValue)"
      conditionA = false
    }
  }

  @IBAction func operator2(sender: UIButton) {
    let operation = sender.currentTitle!
    if conditionA {
      enter()
    }
    switch operation {
    case "✖️": performOperation(multiply)
    default: break
    }
  }
 
  func performOperation(operation: (Double,Double) -> Double) {
    if operandStack.count >= 2 {
      numsValue = operation(operandStack.removeLast(), operandStack.removeLast())
      println("numsValue is \(numsValue)")
      enter()
    }
  }
 
  func multiply(op1: Double, op2: Double) -> Double {
    return op1 * op2
  }


}


위데 색깔 들어가 있는 부분만 볼건데...

일단 빨간 부분...


파라미터가 operation: (Double,Double)->Double 이자나.

operation: 부분을 이해 못해서 한참 헤맸어.


일단 그 부분을 빼면은 더블형 두개를 파라미터로 받아서 더블형을 반환하는 함수인데...

performOperation 함수를 암만 봐도 return 이 없잖아.

그래서 이게 어떻게 된 건지 한참을 봤는데...


operation: (Double,Double)->Double 부분이 ( ) 로 감싸여져 있잖아.

이건 이 함수의 input 값과 return 값을 나타내는게 아니라 그냥 그 전체가 input parameter 라는 얘기지...

즉 더블형 두개를 받아서 더블형을 반환하는 operation 함수를 입력 파라미터로 받는 다는 얘기.


한참 헤맸네...


위에서 performOperation 를 호출 한 부분을 보면 

case "✖️": performOperation(multiply)

그 입력 값은 multiply가 되지.


그러면 performOperation 의 입력값은

multiply: (Double,Double)->Double 가 되는가봐.


즉 더블형 두개를 입력받고 더블형을 반환하는 multiply 라는 함수가 입력값이 되지.


이제 이 함수 선언 부분을 이해했으니까 그 안을 들여다 보자고.


그냥 다른 부분은 넘어가고 제일 중요한 부분이

numsValue = operation(operandStack.removeLast(), operandStack.removeLast())

여기서 operation 은 multiply 이니까 multiply 함수를 호출해서 반환 받은 값을 numsValue 변수에 넣어 주는거야.


입력값은 operandStack 배열의 마지막 값과 두번째 마지막 값.

뭐 다른 부분은 쉽게 이해가 가서 별로 정리해 둘 건 없고.


swift 에서 제공하는 함수 축약해서 사용하는 방법을 이 부분에서 설명이 되니 그거나 정리해야 겠다.




  func multiply(op1: Double, op2: Double) -> Double {
    return op1 * op2
  }


이 부분을 축약해서 case 문 안에 넣는 거야.


case "✖️": performOperation({ (op1: Double, op2: Double) -> Double in
      return op1 * op2 })


이것도 축약할 수 있는데.



multiply 함수가 더블형 파라미터 두개를 전달 받아서 더블형 을 반환 하는 것은 이미 함수에서 선언 했으니까 그 부분은 이렇게 생략해도 됨.


case "✖️": performOperation({ (op1, op2) in return op1 * op2 })


그리고 return 를 생략해도 되고..


case "✖️": performOperation({ (op1, op2) in op1 * op2 })


여기서 더 줄일 수 있는데..
multiply 함수에 두개의 더블형 파라미터가 전달 되는 것은 이미 알고 있으니까 그냥 아래 처럼 해도 된대.


case "✖️": performOperation({ $0 * $1 })


그리고 그냥 괄호도 없애 버리고 이렇게 해도 되고.


case "✖️": performOperation{ $0 * $1 }


swift는 이런 부분에서 굉장히  flexible 한 것 같애.


이게 원래 계산기 앱 소스코드인데.. 이렇게 축약하면 곱하기 나누기 더하기 빼기 모두 다 집어 넣어서 소스코드를 아래와 같이 간략하게 만들 수 있어.


import UIKit

class ViewController: UIViewController {
  @IBOutlet weak var nums: UILabel!
  var conditionA = false
 
  @IBAction func CalNums(sender: AnyObject) {
   
    let typed = sender.currentTitle!
   
    if conditionA {
      nums.text = nums.text! + typed!
    } else {
      nums.text = typed
      conditionA = true
    }
  }

  var operandStack = Array<Double>()
  @IBAction func enter() {
    conditionA = false
    operandStack.append(numsValue)
    println("operandStack = \(operandStack)")
  }
 
  var numsValue: Double{
    get {
      return NSNumberFormatter().numberFromString(nums.text!)!.doubleValue
    }
    set {
      nums.text = "\(newValue)"
      conditionA = false
    }
  }

  @IBAction func operator2(sender: UIButton) {
    let operation = sender.currentTitle!
    if conditionA {
      enter()
    }
    switch operation {
    case "✖️": performOperation{ $0 * $1 }
    case "➗": performOperation{ $0 / $1 }
    case "➕": performOperation{ $0 + $1 }
    case "➖": performOperation{ $0 - $1 }
    default: break
    }
  }
 
  func performOperation(operation: (Double,Double) -> Double) {
    if operandStack.count >= 2 {
      numsValue = operation(operandStack.removeLast(), operandStack.removeLast())
      println("numsValue is \(numsValue)")
      enter()
    }
  }
}




오늘 아주 좋은 걸 배웠어.. :)

그 강좌 계속 따라가면서 저 계산기 앱 마저 완성하면 swift도 많이 익숙해 질 것 같네....


반응형