Xcode Playground中运行data(using:)方法发送报错。
let text = "Hello, Swift!"
if let binaryData = text.data(using: .utf8) {
print(binaryData) // 打印二进制数据
}
报错内容为:
Cannot infer contextual base in reference to member 'utf8'
Value of type 'String' has no member 'data'
经排查发现,问题为缺少Foundation框架。
因为data(using:)方法属于Foundation框架,因此需要在文件的顶部引入Foundation框架:
import Foundation
重新运行后,问题得到解决。