デバッグプリントで使える予約語と、便利なデバッグプリントメソッド
デバッグプリントで使える予約語
swiftには、デバッグで使える予約語があります。 とはいえ、使う予約語はそこまで多くありませんが、デバッグを行う上で、とても便利です。
Literal | Type | Value |
---|---|---|
#file | String | The name of the file in which it appears. |
#line | Int | The line number on which it appears. |
#column | Int | The column number in which it begins. |
#function | String | The name of the declaration in which it appears. |
#dsohandle | String | The dso handle. |
通常の使い方は、以下のように書くことで、「どのメソッドで」「どこで(行番号)」のような場所を特定しやすいものとして記述ができます。
print("Function: \(#function), line: \(#line)")
メソッドを用意して簡単デバッグプリント
また、メソッドを用意しておくことで、定型でデバッグプリントをどこでも使えるようになります。
たとえば、debug.swiftというファイルを用意して、以下のメソッドを記述しておきます。
public func debugLog(object: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
#if DEBUG // → 必要に応じてコメントアウト
let className = (fileName as NSString).lastPathComponent
print("<\(className)> \(functionName) [#\(lineNumber)]| \(object)\n")
#endif
}
上記記述を書いてプロジェクトに置いておくだけで、どのswiftファイルでもメソッドアクセスできるので、
debugLog(object:"デバッグメッセージ")
という感じで簡単にデバッグプリントを出力させることができます。
swift2.1だとちょっと違う
ちなみに、swift2.1以下(objective-cでも使える)だと以下のような予約語になります。 swift2.1以下を使っている人はほぼ居ないかもしれませんが、参考までに記載しておきます。
Literal | Type | Value |
---|---|---|
__FILE__ |
String | The name of the file in which it appears. |
__LINE__ |
Int | The line number on which it appears. |
__COLUMN__ |
Int | The column number in which it begins. |
__FUNCTION__ |
String | The name of the declaration in which it appears. |