Подтвердить что ты не робот

Есть ли способ получить номер строки и имя функции на языке Swift?

В Objective-C мы можем использовать макросы __LINE__ и __PRETTY_FUNCTION__. Они не отображаются на языке Swift. Есть ли другой способ получить подобную информацию в Swift?

4b9b3361

Ответ 1

Swift Language Reference определяет несколько "специальных литералов", которые предлагают такое поведение:

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.

Ответ 2

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.

Пример

print("Function: \(#function), line: \(#line)") 

Со значениями по умолчанию в параметрах вы также можете создать функцию

public func track(_ message: String, file: String = #file, function: String = #function, line: Int = #line ) { 
    print("\(message) called from \(function) \(file):\(line)") 
}

который можно использовать таким образом

track("enters app")

См. документацию для получения дополнительной информации https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID390


В Swift 2.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.

Пример

print("Function: \(__FUNCTION__), line: \(__LINE__)") 

Ответ 3

Вы можете получить только имя файла таким образом.

let errorLocation =  (#file as NSString).lastPathComponent
print(errorLocation)

или

let errorLocation = filePath.components(separatedBy: "/").last!
print(errorLocation)

вывод

ViewController.swift