swift和OC的自定義Log有一些不同,具體代碼如下
//// AppDelegate.swift// Test//// Created by fe on 2017/03/03.// Copyright © 2017年 fe. All rights reserved.//import UIKit@UIapplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. MyLog(message: "hello world") return true }}//自定義Log/* 1:自定義Log一般寫在AppDelegate文件中,作為一個全局函數,在整個項目中都可以調用 2:<T>:表示參數可以是任意類型,<>內的文字可以任意寫 3:file:String = #file ,使用默認參數獲取到打印語句所在的類名,#file相當于OC和swift3.0前的__FILE__ 4:funcName:String = #function ,使用默認參數獲取到打印語句所在的方法名,#function相當于OC和swift3.0前的__FUNCTION__ 5:lineNum:Int = #line ,使用默認參數獲取到打印語句所在的行號,#line相當于OC和swift3.0前的__LINE__ */func MyLog<T>(message:T,file:String = #file,funcName:String = #function,lineNum:Int = #line){ let fileName = (file as NSString).lastPathComponent PRint("/(fileName)---->row/(lineNum)---->/(message)")}自定義Log還有一個重要的用途,就是可以讓這些輸出語句在Debug的編譯環境下可以打印,在Release環境下不能打印輸出,節省性能,需要配置一下編譯狀態,以便輸出時候做判斷,如下圖
然后在打印方法中做這樣的判斷,代碼如下
func MyLog<T>(message:T,file:String = #file,funcName:String = #function,lineNum:Int = #line){ #if DEBUG let fileName = (file as NSString).lastPathComponent print("/(fileName)---->row/(lineNum)---->/(message)") #endif}
新聞熱點
疑難解答