Print Class Name of Current File in Swift

前端 未结 6 1582
[愿得一人]
[愿得一人] 2020-12-30 03:36

I\'m trying to print the name of the current class in Swift. More specifically, I\'d like achieve the following output:

myFunction() in ClassContainingTheFun         


        
6条回答
  •  礼貌的吻别
    2020-12-30 03:59

    I wanted a solution that logged out a nice neat string like this (Swift 3.0) - Class Name - Function Name. eg :

    OnboardingGetStartedController - viewDidLoad()

    So I ended up with a short function that Ive put in my utils class, like this :

    class func logCurrentFunc(fileStr: String, funcStr: String) {
    
        var fileName = fileStr.components(separatedBy: "/").last ?? ""
        fileName = fileName.components(separatedBy:".").first ?? ""
        let printFunc = "\(fileName) - \(funcStr)"
        print(printFunc)
    }
    

    And I call this from anywhere in the app, like this :

    Utils.logCurrentFunc(#file, funcStr: #function)
    

    Its just a bit neater looking than other suggestions.

提交回复
热议问题