在Swift中重写NS ***方法 [英] Overriding NS*** methods in Swift

查看:354
本文介绍了在Swift中重写NS ***方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了提供NSLocalizedString的后备语言,我在Objective-C中使用了#undef#define:

To provide a fallback language for NSLocalizedString, I'm using this #undef and #define in Objective-C:

#undef NSLocalizedString
#define NSLocalizedString(key, comment) @"NSLocalizedString has been replaced";

如果从Objective-C调用,则效果很好,但是,如果从Swift调用,则将忽略NSLocalizedString的新定义. (桥接头已正确配置并且可以工作)

This works perfectly well if called from Objective-C, but if called from Swift, the new definition of NSLocalizedString is ignored. (bridging header is configured correctly and works)

在Swift中有可能吗?如果可以,怎么办?

Is this possible in Swift, and if so, how?

注意:真实的示例是在Github上,另请参见

Note: the real example is here on Github, also see SO answer here

推荐答案

您可以为NSObject这样的子类执行此操作

You can do this for NSObject subclasses like this

extension NSObject {
    func NSLocalizedString(key: String, comment: String) -> String {
        return "yes we have localized an NSObject"
    }
}

AnyObject怎么样?在这种情况下,您必须了解并遵守AnyObject子类中的FallbackLanguage协议

What about AnyObject? In this case, you would have to be aware of and conform to the FallbackLanguage protocol in your AnyObject subclass

protocol FallbackLanguage: class {}

// add default implementations
extension FallbackLanguage {
    func NSLocalizedString(key: String, comment: String) -> String {
        return "yes we have localized AnyObject via FallbackLanguage protocol"
    }
}


注释

  • 这两个解决方案都可以在您的项目中使用,没有任何问题.
  • 如果您要在类实例之外调用NSLocalizedString,那么您就不走运了.
  • These two solutions can both be in your project without any issues.
  • If you're calling NSLocalizedString outside of a class instance, you're out of luck.

这篇关于在Swift中重写NS ***方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆