Swift

[Swift]フォルダ作成

フォルダ作成

private func mkDir(path:String) -> Bool{
    let _path = NSHomeDirectory().stringByAppendingPathComponent("Documents/" + path)
    var error: NSError? = nil
    return NSFileManager.defaultManager().createDirectoryAtPath(_path, withIntermediateDirectories: true, attributes: nil, error: &error)
}

[Swift]Documentsフォルダ内のファイル一覧出力

Documentsフォルダ内のファイル一覧出力

private func getFileNames(dir:String) -> [String]{
    let path = NSHomeDirectory().stringByAppendingPathComponent("Documents/" + dir)
    var error: NSError? = nil
    let fileNames:[AnyObject] = NSFileManager.defaultManager().contentsOfDirectoryAtPath(path,error:&error)!
    var tmp:[String] = []
    for fileName:AnyObject in fileNames {
        tmp.append(fileName as String)
    }
    return tmp
}
private func logFileNames(){
    println("----------------- " + __FUNCTION__ + "---------------------")
    let files:[String] = self.getFileNames("")
    for n:String in files {
        println("\(n)")
    }
}

[Swift]NSTimer

NSTimer

NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "showInfo", userInfo: nil, repeats: false)

func showInfo(){
    println("あいうえお")
}

[Swift]ログメソッド

ログメソッド

func LOG(message:String = "", file:String = __FILE__, funcName:String = __FUNCTION__, line:Int = __LINE__) {
    #if DEBUG
        var f:String = file.componentsSeparatedByString("/").last!
        var cnt:Int = 45 - f.utf16Count
        while 0 < cnt {
            f += " "
            cnt--
        }
        var sline:String = String(line)
        cnt = 4 - sline.utf16Count
        while 0 < cnt {
            sline = " "+sline
            cnt--
        }
        if message.isEmpty {
            println("\(f) - \(sline) - \(funcName)")
        }else{
            println("\(f) - \(sline) - \(funcName)\n -> \(message)")
        }
    #endif
}

出力結果

ViewController.swift                          -   65 - onChangeTimeScale
 -> selectedIndex : 0

[Swift]objective-cで書かれたクラスを扱う

objective-cで書かれたクラスを扱う

1.「Common-Bridging-Header.h」というヘッダーファイルを作成する
*ファイル名は任意

2.Common-Bridging-Header.hに下記を記述する

#import "EGODatabase.h"

3.PROJECT -> Build Settings -> Swift Compiler – Code Generation
-> Objective-C Bridging Headerに作成したファイル名を設定する
Objective-C Bridging Header

4.普通に扱う

let ego:EGODatabase = EGODatabase(path: "\(NSHomeDirectory())/Documents/ultrawoman.db")
private init(){
    self._initSystemTable()
}
private func createTableWithTableName(tableName:String, columnInfo:String) -> Bool{
    let query:String = "CREATE TABLE IF NOT EXISTS '\(tableName)' (\(columnInfo));"
    let result:EGODatabaseResult = self.ego.executeQuery(query)
    if 0 < result.errorCode {
        return false
    }
    return true
}
private func _initSystemTable(){
    let table:String = "id INTEGER PRIMARY KEY AUTOINCREMENT,key TEXT DEFAULT '',value TEXT DEFAULT '',modified TEXT,created TEXT"
    let result:Bool = self.createTableWithTableName(self.tableNameOfSystem, columnInfo: table)
}

[Swift]AutoLayout後のframeを取得

AutoLayout後のframeを取得

override func viewDidLoad() {
    super.viewDidLoad()
    let width:CGFloat = self.someView.frame.size.width//AutoLayout前の値が取得できる
}
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    let width:CGFloat = self.someView.frame.size.width//AutoLayout後の値が取得できる
}

[Swift]クラス名取得

クラス名取得

設定

extension UIViewController {
    var className:String{
        get{
            return NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
        }
    }
}

実行

println("\(self.className) - \(__FUNCTION__) \(__LINE__) @ \(__FILE__)")

[Swift]IBOutlet,IBAction

IBOutlet,IBAction

@IBOutlet var button:UIButton?
@IBAction func onTapButton(sender:AnyObject){
    println("onTapButton")
    var button:UIButton = sender as UIButton
}

[Swift]クロージャ

クロージャ objective-cにおけるブロック

宣言

typealias ChangeMonthClosureType = (year:Int,month:Int) -> () //型に別名を付ける
var closureOnChangeMonth:ChangeMonthClosureType?

設定

self.msvc.closureOnChangeMonth = {
    (year:Int,month:Int) -> () in
    println("closureOnChangeMonth year:\(year) month:\(month)")
}

実行

self.closureOnChangeMonth?(year: self._year, month: self._month)