2014-06-08 7 views
29

उद्देश्य-सी में, हम __LINE__ और __PRETTY_FUNCTION__ मैक्रोज़ का उपयोग कर सकते हैं। ये स्विफ्ट भाषा में प्रकट नहीं हैं। स्विफ्ट में समान जानकारी प्राप्त करने का कोई और तरीका है?स्विफ्ट भाषा में लाइन नंबर और फ़ंक्शन नाम प्राप्त करने का कोई तरीका है?

उत्तर

26

Swift Language Reference defines कुछ "विशेष शाब्दिक" है कि इस व्यवहार की पेशकश:

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

यह अब और अद्यतन नहीं किया गया है। स्विफ्ट 3 इस स्थिर को अद्यतन करें। @hfossli जवाब अब सही है। – jollyr0ger

+1

@ jollyr0ger यही "संपादन" बटन है: डी – 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. 

उदाहरण

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


स्विफ्ट 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

स्विफ्ट 2.2 परिवर्तन अब जारी किए गए हैं और नया स्वीकृत उत्तर होना चाहिए :) – Bersaelor

+1

'#' 2.2 में हो रहा है। –

+0

# नामस्थान एक पहचानकर्ता नहीं है। – c0ming

0

आप इस तरह से फ़ाइल का नाम प्राप्त कर सकते हैं।

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

या

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

उत्पादन

ViewController.swift 
संबंधित मुद्दे

 संबंधित मुद्दे