1. 程式人生 > >Swift_自定義log

Swift_自定義log

   print(#file) //獲取當前當前print所在的檔案路徑

   print(#function) //獲取s當前print所在的方法名稱

   print(#line) //獲取當前pring所在的行號

根據這些我們可以建立建立一個方法

/// - Parameters:

///   - message: 列印的資訊

///   - fileName: 檔名稱

///   - methodName: 方法名

///   - lineNumber: 行號

func NSLog<T>(message : T, fileName : String = #file, methodName : String = #function, lineNumber : Int = #line) {

    #if DEBUG

     //     print("\((fileName as NSString).pathComponents.last!.description)--\(methodName)-[\(lineNumber)]: \(message)")

        print("\(methodName)-[\(lineNumber)] 列印資料: \(message)")

    #endif

}

這個方法我們放在自己建立的 Swift File這樣就能全域性使用了。然後我們需要在專案中進行一下設定確保只有在Debug模式下才列印資料

在Build Settings下面的Other Swift Flags 中開啟,包含兩種模式,一定注意選擇Bebug之後新增 -D DEBUG,這樣才能實現只有在debug模式下列印。如果release模式下也列印那就是你新增錯了(release 模式下一定不包含 -D DEBUG)