2014-06-08 2 views

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. 
+3

Questo non è più aggiornato. Swift 3 aggiorna questa costante. @hfossli risposta è quella giusta ora. – jollyr0ger

+1

@ jollyr0ger ecco a cosa serve il pulsante "modifica": D – Fogmeister

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__)") 
+3

Le modifiche di Swift 2.2 sono ora rilasciate e dovrebbero essere la nuova risposta approvata :) – Bersaelor

+1

'# sta accadendo in 2.2. –

+0

#namespace non è un identificatore. – c0ming

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