Swift 将 NSLocalizedString 传递给 NSObject 参数的方法无法编译

Swift method passing NSLocalizedString to NSObject parameter won't compile

我不得不修改一个 Objective-C 方法来获取一个 NSObject 参数,该参数实际上应该是 NSStringNSLocalizedString。最初该方法被声明为采用 NSString 参数,但我需要能够传递 NSStringNSLocalizedString 的灵​​活性,令我沮丧的是我发现它只有 NSObject 作为共同的祖先。

对 Objective-C 方法的参数类型的这种更改给一些现有的 Swift 代码带来了问题,这些代码使用传入的 NSLocalizededString 参数调用该方法:

NSLocalizedString('random key', comment: 'Key name')

这是实际代码,我认为它不会更有启发性:

appDelegate.menuOverlayViewController.showPopup(withStateName: "didRequestTrackChange", 
withTitle: NSLocalizedString("localization.popup.title", comment: "Success!"), 
withIconName: "icon_like", 
withBody:body)

未修改,代码产生此错误:

Cannot convert value of type 'String' to expected argument type 'NSObject!'

如果我尝试像这样将 NSLocalizedString 转换为 NSObject

NSObject(NSLocalizedString('random key', comment: 'Key name'))

我运行进入如下错误:

Argument passed to call that takes no arguments

我该如何解决这个问题?我对 Swift 比较陌生,所以不明白我将如何施放某些东西的细微差别,或者为什么 NSLocalizedString 显然在得到之前就变成了 Swift String传递给 NSObject.

类型的参数

而不是

NSObject(NSLocalizedString('random key', comment: 'Key name'))

尝试

(NSString(string :NSLocalizedString('random key', comment: 'Key name'))

编辑:

NSLocalizedString('random key', comment: 'Key name') as! NSObject

一个Swift String不是一个对象,而是一个struct。如果要对 NSStringNSLocalizedString 使用 NSObject,请将 Swift String 转换为 NSString.

"my string" as NSString

或者,考虑使用协议并扩展 NSStringNSLocalizedString 以符合它。