Showing posts with label Swift. Show all posts
Showing posts with label Swift. Show all posts

Saturday, April 29, 2017

iOS Swift 요약 정리

init? 실패할수도 있는(nil을 리턴할수 있는) 생성자
A ?? B 3항 연산자로 unwrapping이 가능하면 unwrapping 실패하면 B를 리턴

Optional - nil을 가질수 있음. 그리고 할당하지 않으면 nil임
? - 언래핑 해야함
!  - 암묵적 언래핑이 되어 있어서 !를 붙여서 언래핑 할필요 없음

Casting
as NSString  - 다운캐스팅
as! NSString - 업캐스팅. 실패시 에러
as? NSString - 옵셔널캐스팅. 실패시 false 리턴. if절에서 체크

if let, var 언래핑 where

Guard
일반적으로 에러처리해서 함수에서 리턴하는 명령들이다
guard let number = value where value < 10 else {
    // false시 처리할 문장
    return
}

do while => repeat while

Switch
0..49가능 where 가능
fallthrough break없이 다음 case까지 진행가능

String formatting
print(“\(userName)”)

Function
func funcName(var1:int, var2: int) -> Float
{
}

Class static method
class ClassName
{
    class func funcName
}

함수에 변수 포인터 전달
inout

생성자/소멸자
init()
deinit()

계산된 속성
var balance: Float {
    get {
        return _balance
    }
    set(newBalance) {
        _balance = newBalance
    }
}


접근자
open, public
internal (default)
fileprivate
private


do catch
try func() - exception을 throw하는 경우에는 이렇게 호출해야함
try! func() - throw하는 함수에 대해서 에러처리를 받지 않고 호출함

enum ZZZException : ErrorType {
case XXX
case YYY
}

defer - 함수 종료시에 무조건 호출되는 함수를 지정

이 예제에서 class타입은 override할 수 있지만, static타입은 컴파일 에러를 발생시키네요.
static타입 선언은 class final선언과 같다고 볼 수 있습니다.

클로저
let multiply = {(val1: Int, val2: Int) -> Int in
    return val1*val2;
}

Friday, July 1, 2016

iOS Swift 키보드 show/hide 시 UI 위치 보정 처리

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        registerForKeyboardNotifications()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        unregisterForKeyboardNotifications()
    }

    //MARK: Keyboard events
    func registerForKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow), name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide), name: UIKeyboardWillHideNotification, object: nil)
    }

    func unregisterForKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
    }
    
    func keyboardWillShow(note: NSNotification) {
        // UI 키보드 위로 올려준다
        print("keyboardWillShow")

        let s = note.userInfo![UIKeyboardFrameEndUserInfoKey]
        let rect = s!.CGRectValue()
        
        // 입력창 위치를 올려줌
        var frame = textField.frame
        frame.origin.y -= rect.height
        textField.frame = frame

        let keyboardFrameEnd = view!.convertRect(rect, toView: nil)
        view.frame = CGRectMake(0, 0, keyboardFrameEnd.size.width, keyboardFrameEnd.origin.y)
        view.layoutIfNeeded()
    }
    
    func keyboardWillHide(note: NSNotification) {
        // UI 원위치 한다
        print("keyboardWillHide")

        let s = note.userInfo![UIKeyboardFrameBeginUserInfoKey]
        let rect = s!.CGRectValue()

        var frame = textField.frame
        frame.origin.y += rect.height
        textField.frame = frame
        
        frame = view.frame
        view.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.width, frame.height + rect.height)
        view.layoutIfNeeded()
    }

Monday, June 27, 2016

iOS Swift NSThread 생성하기

selector의 구문이 바뀌었다.
self 클래스에 runLoop()가 있어야 한다.

            let thread = NSThread(target:self, selector:#selector(runLoop), object: nil)
            thread.start()
  
func runLoop() {
        while(true) {
            print("runLoop")
        }
    }