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}
新闻热点
疑难解答