17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

My Swift Snipets

Last updated at Posted at 2014-07-10

SwiftでMacアプリをつくっていて、
ちょっとハマった所。スニペットにしてまとめました。
随時更新予定。

GCD

gcd_sample.swift

// dispatch_get_main_queueは廃止
// 5秒後に
let offset = 5.0
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(offset * Double(NSEC_PER_SEC))),dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),{
	// TODO dispatch
})

// Background Task
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, {
  // Background
})

デリゲート定義

とてもいいまとめ↓
http://fuckingclosuresyntax.com/

delegate_sample.swift
class TheDelegteSample {
	// 定義
	typealias JsonDelegate = (json:NSDictionary) -> ()
	
	// 変数
	var jsonDelegate:JsonDelegate?

	// 叩く
	func foo() {
		if jsonDelegate {
			jsonDelegate(json:theJson)
		}
	}
}

Obj-C側でswift用のデリゲートを定義するのはこちら。

delegate_sample.h

typedef void (^JsonDelegate)(NSDictionary json);

シングルトン

file_sample.swift

class TheSingleton: NSObject {
	
	// スタティックgetter変数はclass var
	// structじゃないとスタティックプロパティは持てない
    class var instance : TheSingleton {
        struct Singleton {
            static let _instance = TheSingleton()
        }
        return Singleton._instance
    }
}

日にち

date_sample.swift

let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.setDateFormat("yyyy-MM-dd-HH-mm-ss")
let dateStr = dateFormatter.stringFromDate(date)

ファイル

file_sample.swift

// デスクトップから取得。構造体になってるので注意
let directory = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DesktopDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let directoryStr = directory[0] as NSString
let path = NSString(format: "%@/%@.txt", directoryStr, "thefile")        
let url = NSURL(fileURLWithPath:path)

音再生(Mac)

SoundManager.swift

import Cocoa

class SoundManager {
    
    struct Cache {
        static let sound = Dictionary<String, NSSound>()
    }
    
    
    init() {
    }
    
    class func getSound(name:String) -> NSSound {
        var sound = Cache.sound[name]
        
        if sound == nil  {
            let soundpath = NSBundle.mainBundle().pathForResource(name, ofType:"aif")
            sound = NSSound(contentsOfFile: soundpath, byReference: false)
        }
        
        return sound!
    }
    
    class func play(name:String) {
        let sound = SoundManager.getSound(name)
        sound.play()
    }
}

17
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?