Is there a Swift alternative for NSLog(@“%s”, __PRETTY_FUNCTION__)

前端 未结 11 1152
梦谈多话
梦谈多话 2020-12-02 07:39

In Objective C you can log the method that is being called using:

NSLog(@\"%s\", __PRETTY_FUNCTION__)

Usually this is used from a logging m

11条回答
  •  臣服心动
    2020-12-02 08:20

    As of XCode beta 6, you can use reflect(self).summary to get the class name and __FUNCTION__ to get the function name, but things are a bit mangled, right now. Hopefully, they'll come up with a better solution. It might be worthwhile to use a #define until we're out of beta.

    This code:

    NSLog("[%@ %@]", reflect(self).summary, __FUNCTION__)
    

    gives results like this:

    2014-08-24 08:46:26.606 SwiftLessons[427:16981938] [C12SwiftLessons24HelloWorldViewController (has 2 children) goodbyeActiongoodbyeAction]
    

    EDIT: This is more code, but got me closer to what I needed, which I think is what you wanted.

    func intFromString(str: String) -> Int
    {
        var result = 0;
        for chr in str.unicodeScalars
        {
            if (chr.isDigit())
            {
                let value = chr - "0";
                result *= 10;
                result += value;
            }
            else
            {
                break;
            }
        }
    
        return result;
    }
    
    
    @IBAction func flowAction(AnyObject)
    {
        let cname = _stdlib_getTypeName(self)
        var parse = cname.substringFromIndex(1)                                 // strip off the "C"
        var count = self.intFromString(parse)
        var countStr = String(format: "%d", count)                              // get the number at the beginning
        parse = parse.substringFromIndex(countStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
        let appName = parse.substringToIndex(count)                             // pull the app name
    
        parse = parse.substringFromIndex(count);                                // now get the class name
        count = self.intFromString(parse)
        countStr = String(format: "%d", count)
        parse = parse.substringFromIndex(countStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
        let className = parse.substringToIndex(count)
        NSLog("app: %@ class: %@ func: %@", appName, className, __FUNCTION__)
    }
    

    It gives output like this:

    2014-08-24 09:52:12.159 SwiftLessons[1397:17145716] app: SwiftLessons class: ViewController func: flowAction
    

提交回复
热议问题