Swift中的base64EncodedStringWithOptions失败,出现编译错误 [英] base64EncodedStringWithOptions in Swift fails with compile error
问题描述
let dataStr = data.base64EncodedStringWithOptions(options: Encoding64CharacterLineLength)
不与使用未解析的标识符'Encoding64CharacterLineLength'一起编译" 当我只是使用
Doesn't compile with "Use of unresolved identifier 'Encoding64CharacterLineLength'" When I just change the param to zero with
let dataStr = data.base64EncodedStringWithOptions(options: 0)
它甚至给出了一个陌生的错误:无法转换类型为'String!的表达式!键入"String!".我找到了一种使用NSData初始化NSString的方法(但是,我仍然无法得到String和NSString之间的区别),但我真的很好奇为什么这两行代码不起作用.
It gives even stranger error: "Cannot convert the expression of type 'String!' to type 'String!'" I found a way to init NSString with NSData (however, I still can't get the difference between String and NSString), but I'm really curious why these two lines of code don't work.
推荐答案
除非显式给出外部名称,否则Swift中方法的第一个参数不是命名参数.因此,您应该这样做:data.base64EncodedStringWithOptions(x)
没有options:
部分.
Unless explicitly given an external name, first argument of a method in Swift is not a named argument. Therefore you should be doing: data.base64EncodedStringWithOptions(x)
without the options:
part.
如果您实际查看参数类型NSDataBase64EncodingOptions
,您会注意到它是一个符合RawOptionSet
的结构,带有用于选项常量的静态变量.因此,要使用它们,您应该执行以下操作:NSDataBase64EncodingOptions.Encoding64CharacterLineLength
If you actually look at the argument type, NSDataBase64EncodingOptions
, you'll notice that it is a struct conforming to RawOptionSet
with static variables for option constants. Therefore to use them you should do: NSDataBase64EncodingOptions.Encoding64CharacterLineLength
NSDataBase64EncodingOptions
结构(或通常为RawOptionSet
)也不能从整数文字(如0
)转换.但是它确实符合NilLiteralConvertible
的要求,因此如果您不希望使用任何选项,则可以传递nil
.
The NSDataBase64EncodingOptions
struct (or RawOptionSet
in general) is also not convertible from integer literals (like 0
). But it does conform to NilLiteralConvertible
so if you don't want any options you can pass nil
.
放在一起:
let dataStr = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
或
let dataStr = data.base64EncodedStringWithOptions(nil)
Swift3.0
let dataStr = data.base64EncodedString(options: [])
这篇关于Swift中的base64EncodedStringWithOptions失败,出现编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!