我怎么打电话
print(NSDate()) 而不是接收通常的响应,而是在一个名为getString()的函数中获得一个响应,该函数是extension of NSDate的一部分。
这是我的分机:
extension NSDate {
//NSDate to String
public func getString() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateFormatter.locale = NSLocale.currentLocale()
return dateFormatter.stringFromDate(self)
}
}请注意,我不想只使用: NSDate().getString() 我想重写这个类的原始
description。
更新:
因此,一切看起来都是唯一的选项,如果可能的话,就是方法Swizzling。 有人对赏金感兴趣吗?
领导
我这么做只是为了个人成长,并了解这个概念,而不是计划在这个场景中使用它的应用程序,甚至现在还不确定我可以在什么样的场景中使用它。
发布于 2016-03-04 23:11:08
import Foundation
extension NSDate: Streamable {
public func writeTo<Target : OutputStreamType>(inout target: Target) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateFormatter.locale = NSLocale.currentLocale()
print("without swizzling", dateFormatter.stringFromDate(self), toStream: &target)
}
}
let date = NSDate()
print(date) // without swizzling 2016-03-05 00:09:34 +0100打印“默认”/原始行为/使用
print(date.description)如果您担心在扩展中使用打印,只需将其替换为
//print("without swizzling", dateFormatter.stringFromDate(self), toStream: &target)
let str = dateFormatter.stringFromDate(self)
str.writeTo(&target)发布于 2016-03-04 22:18:01
我很确定这是个可怕的,坏的,不好的,可怕的主意。但给你的是:
extension NSDate {
private static let dateFormatter = NSDateFormatter()
private static var once = dispatch_once_t()
static func swizzleDescription() {
dispatch_once(&once) {
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateFormatter.locale = NSLocale.currentLocale()
let originalMethod = class_getInstanceMethod(self, "description")
let replacementMethod = class_getInstanceMethod(self, "description_terribleIdea")
method_exchangeImplementations(originalMethod, replacementMethod)
}
}
func description_terribleIdea() -> String {
return NSDate.dateFormatter.stringFromDate(self)
}
}
let date = NSDate()
print(date)
NSDate.swizzleDescription()
print(date)输出:
2016-03-04 22:17:20 +0000
2016-03-04 16:17:20 -0600发布于 2016-03-08 07:21:21
可以定义您自己的打印版本:
func print(date: NSDate) {
print(date.getString())
}
extension NSDate {
//NSDate to String
public func getString() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateFormatter.locale = NSLocale.currentLocale()
return dateFormatter.stringFromDate(self)
}
}这两个调用现在将打印相同的内容:
let date = NSDate()
print(date.getString())
print(date)https://stackoverflow.com/questions/35159726
复制相似问题