我使用Obj-C编写的NSData
base64Encoding
类别。
@interface NSData (Base64)
+ (NSData*)dataFromBase64String:(NSString*)aString;
- (NSString*)base64EncodedString;
@end
最初在Swift 2.2中,我使用它作为:
let dbPassData = NSData(fromBase64String: password)
现在,在Swift 3中,没有任何NSData
,而是Data
。
如何在swift 3中使用这些类别方法?
将项目转换为Swift 3后,它将该行转换为:
let dbPassData = Data(fromBase64String: password)
产生错误:
参数标签与任何可用的重载都不匹配
答案 0 :(得分:0)
In Swift 3, Apple also renamed some initializers and Xcode 8 beta makes some mistakes when converting from 2.2 to 3.
In that case, the initializer was renamed to this:
let data = Data(base64Encoded: "hello")
When you are facing this or similar problems, you can start typing ClassName(
and look at the proposed initializers. In most cases, you'll find the new one easily.
答案 1 :(得分:0)
NSData
仍可在Swift 3中使用,就像String
与NSString
共存一样。在这种情况下,您需要忽略编译器的建议:
let dbPassData = NSData(fromBase64String: password) as Data
这假设您不希望将Base64
类别移植到Swift,或者希望保持与Obj-C代码的兼容性。 Swift 3的Data
还提供内置的Base 64转换:
let dbPassData = Data(base64Encoded: password)
let base64String = data.base64EncodedString(options: [.lineLength64Characters, .endLineWithLineFeed])