我正在使用下面的公共(public)方法将 API 数据类型转换为 Int。
public func convertToInt( value : Any) -> Int{
if let v = value as? String {
if let myNumber = NSNumberFormatter().numberFromString(v) {
return myNumber.integerValue
} else {
print ("Cannot convert to Int...")
}
} else if let v = value as? Int {
return v
} else if let v = value as? NSNumber {
return v.integerValue
}
return 0
}
我在我的项目中同时使用了 swift 和 objective c 文件。我也想将此函数访问到 objective-c 文件中。如果有人知道解决方案,请帮助我。
最佳答案
问题在于 global Swift functions are unavailable to Objective-C ,并且协议(protocol) Any
不能在 Objective-C 中表示。
因此,一种可能的解决方案是将您的函数封装在辅助类中,并使用 AnyObject
作为您的 value
参数——作为 Int
和 String
可以分别自由桥接到 NSNumber
和 NSString
,因此在导入 Foundation 时可以将其视为对象。
@objc final class HelperFunctions : NSObject {
static func convertToInt(value : AnyObject) -> Int {
if let v = value as? String {
if let myNumber = NSNumberFormatter().numberFromString(v) {
return myNumber.integerValue
} else {
print ("Cannot convert to Int...")
}
} else if let v = value as? Int {
print("int")
return v
}
// note that this check is completely redundant as NSNumber is freely bridgable
// to Int – therefore the 'as? Int' check will always get triggered instead
else if let v = value as? NSNumber {
print("nsnum")
return v.integerValue
}
return 0
}
}
尽管如此,这确实不是非常 Swifty 的代码。 NSNumber
可桥接到 Int
,因此您可以直接转换它:
let n = NSNumber(integer: 5)
let i = n as Int // 5
并且 Int
已经有一个可以接受字符串的初始化器:
let i = Int("55") // Optional(55)
所以,我真的看不出这个函数在解决什么 Swift 问题。虽然我确实看到了它正在解决的 Objective-C 问题,但出于这个原因,我只是将此函数实现为 Objective-C 文件中的 C 函数。
extern NSInteger convertToInt(id _Nonnull value);
inline NSInteger convertToInt(id _Nonnull value) {
if ([value isKindOfClass:[NSString class]]) {
NSNumberFormatter* f = [[NSNumberFormatter alloc] init];
return [f numberFromString:(NSString*)value].integerValue;
} else if ([value isKindOfClass:[NSNumber class]]) {
return ((NSNumber*)value).integerValue;
}
return 0;
}
如果您真的想要的话,您总是可以将它导入回 Swift 中——然后它将作为一个全局函数可用。但我建议您不要将其导入回 Swift,而是找到一个更 Swifty 的解决方案来解决您的问题。
例如,我建议您使用协议(protocol)和扩展在 Swift 中实现它。您可以定义一个 IntRepresentable
协议(protocol)来表示可以转换为 Int
的类型。这样做的好处是您明确了可以转换为 Int
的类型,而不是让它成为您的便利函数的实现细节。
protocol IntRepresentable {
func _asInt() -> Int?
}
现在您可以扩展字典可以包含的类型并使它们符合 IntRepresentable
。
extension NSString : IntRepresentable {
func _asInt() -> Int? {return Int(self as String)}
}
extension NSNumber : IntRepresentable {
func _asInt() -> Int? {return self.integerValue}
}
// not really necessary, as your dict will be [Whatever:AnyObject],
// so the NSString extension will be used – here for completeness
extension String : IntRepresentable {
func _asInt() -> Int? {return Int(self)}
}
extension Int : IntRepresentable {
func _asInt() -> Int? {return self}
init?(representable:IntRepresentable) {
guard let i = representable._asInt() else {return nil}
self = i
}
}
现在您可以通过执行以下操作将字典从 [Whatever:AnyObject]
转换为 [Whatever:Int]
:
let inputDict = ["foo":"5", "bar":6, "baz":NSNumber(int:5)]
var outputDict = [String:Int]()
for (key, value) in inputDict {
if let value = value as? IntRepresentable {
outputDict[key] = Int(representable: value)
}
}
print(outputDict) // ["baz": 5, "foo": 5, "bar": 6]
如果它能让你感觉更好,你总是可以把它放在一个方便的函数中,尽管我仍然反对全局函数。您可以使用无大小写枚举以避免污染全局命名空间:
enum DictionaryConversion {
static func toIntValues<Key>(dict:[Key:NSObject]) -> [Key:Int] {
var outputDict = [Key:Int]()
for (key, value) in dict {
if let value = value as? IntRepresentable {
outputDict[key] = Int(representable: value)
}
}
return outputDict
}
}
或者只是扩展 Dictionary
本身:
extension Dictionary {
func convertValuesToInt() -> [Key:Int] {
var outputDict = [Key:Int]()
for (key, value) in self {
if let value = value as? IntRepresentable {
outputDict[key] = Int(representable: value)
}
}
return outputDict
}
}
let outputDict = DictionaryConversion.toIntValues(inputDict)
let outputDict = inputDict.convertValuesToInt()
关于ios - 如何访问 objective c 文件中的 swift public 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37541500/