Skip to content

Instantly share code, notes, and snippets.

@sahara-ooga
Last active January 7, 2018 13:54
Show Gist options
  • Save sahara-ooga/a4f73808714623432a2e1e29d2be9260 to your computer and use it in GitHub Desktop.
Save sahara-ooga/a4f73808714623432a2e1e29d2be9260 to your computer and use it in GitHub Desktop.
Swiftで、ファイル名・行番号・列番号・メソッド名を取得する方法

Swiftはじめたい...その10 特殊変数とか参照渡しとか、ジェネリクスとか... - Qiita の、ファイル名・行番号・列番号(行の中で何文字目か)・メソッド名を取得する方法がSwif3で変わっていたのでメモ。

ソースコード

import Foundation

func literalExpression() {
    print("__FILE__",#file)
    print("__LINE__",#line)
    print("__COLUMN__",#column)
    print("__FUNCTION__",#function)
}

literalExpression()

出力結果

__FILE__ ../tmp/literalExpression.swift
__LINE__ 5
__COLUMN__ 24
__FUNCTION__ literalExpression()

ログに使えそう。

ログ関数の作例

func logPrint(strings:String...,
              file:String = #file,
              line:Int = #line,
              column:Int = #column,
              function:String = #function){
    print("logPrint>>>>>>>>>>>>>>>>>>>>>>")
    print("file:",file)
    print("line:",line)
    print("column:",column)
    print("function:",function)
    
    for string in strings {
        print(string)
    }
    
    print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
}

func myFunction(x:Int = 0,y:Int = 0){
    logPrint(strings: "x:"+String(x),"y:"+String(y))
}

myFunction(x: 4, y: 5)

実行結果:

logPrint>>>>>>>>>>>>>>>>>>>>>>
file: mutating.playground
line: 22
column: 13
function: myFunction(x:y:)
x:4
y:5
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

参考

The Swift Programming Language (Swift 4.0.3): Expressions

The Swift Programming Language (Swift 4.0.3): Functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment