In Objective-C, è possibile utilizzare i macro __LINE__
e __PRETTY_FUNCTION__
. Questi non sono esposti nella lingua Swift. C'è un altro modo per ottenere informazioni simili in Swift?C'è un modo per ottenere il numero di riga e il nome della funzione nella lingua Swift?
29
A
risposta
26
Il Swift Language Reference defines alcuni "letterali speciali" che offrono questo comportamento:
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.
91
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.
Esempio
print("Function: \(#function), line: \(#line)")
Con i valori di default dei parametri è possibile anche creare una funzione
public func track(_ message: String, file: String = #file, function: String = #function, line: Int = #line) {
print("\(message) called from \(function) \(file):\(line)")
}
che può essere utilizzato in questo modo
track("enters app")
, consultare la documentazione per ulteriori informazioni https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID390
In Swift 2.1 e di seguito:
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.
Esempio
print("Function: \(__FUNCTION__), line: \(__LINE__)")
0
È possibile ottenere solo il nome del file in questo modo.
let errorLocation = (#file as NSString).lastPathComponent
print(errorLocation)
o
let errorLocation = filePath.components(separatedBy: "/").last!
print(errorLocation)
uscita
ViewController.swift
Questo non è più aggiornato. Swift 3 aggiorna questa costante. @hfossli risposta è quella giusta ora. – jollyr0ger
@ jollyr0ger ecco a cosa serve il pulsante "modifica": D – Fogmeister