我有一个Data类型的变量fileData,我不知道如何打印它的大小。
以前在NSData中可以打印长度,但使用这种类型无法实现。
在Swift中如何打印Data的大小?
我有一个Data类型的变量fileData,我不知道如何打印它的大小。
以前在NSData中可以打印长度,但使用这种类型无法实现。
在Swift中如何打印Data的大小?
func stackOverflowAnswer() {
if let data = #imageLiteral(resourceName: "VanGogh.jpg").pngData() {
print("There were \(data.count) bytes")
let bcf = ByteCountFormatter()
bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
bcf.countStyle = .file
let string = bcf.string(fromByteCount: Int64(data.count))
print("formatted result: \(string)")
}
}
得到以下结果:
There were 28865563 bytes
formatted result: 28.9 MB
如果你的目标是将大小打印到用户界面上,可以使用ByteCountFormatter
import Foundation
let byteCount = 512_000 // replace with data.count
let bcf = ByteCountFormatter()
bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
bcf.countStyle = .file
let string = bcf.string(fromByteCount: Int64(byteCount))
print(string)
NSDimension
用于信息存储(字节)。我有什么遗漏吗? - Alexander您可以使用 Data 对象的 count
,而对于 NSData,您仍然可以使用 length
。
count
。 - abdullahselekSwift 5.1
extension Int {
var byteSize: String {
return ByteCountFormatter().string(fromByteCount: Int64(self))
}
}
用法:
let yourData = Data()
print(yourData.count.byteSize)
根据已接受的答案,我创建了一个简单的扩展:
extension Data {
func sizeString(units: ByteCountFormatter.Units = [.useAll], countStyle: ByteCountFormatter.CountStyle = .file) -> String {
let bcf = ByteCountFormatter()
bcf.allowedUnits = units
bcf.countStyle = .file
return bcf.string(fromByteCount: Int64(count))
}}
一个快速的扩展,可以将Data
大小以兆字节为单位转换成Double
。
extension Data {
func getSizeInMB() -> Double {
let bcf = ByteCountFormatter()
bcf.allowedUnits = [.useMB]
bcf.countStyle = .file
let string = bcf.string(fromByteCount: Int64(self.count)).replacingOccurrences(of: ",", with: ".")
if let double = Double(string.replacingOccurrences(of: " MB", with: "")) {
return double
}
return 0.0
}
}
在下面的代码中输入文件的URL以获取文件大小(以MB为单位),希望这可以帮助您。
let data = NSData(contentsOf: FILE URL)!
let fileSize = Double(data.count / 1048576) //Convert in to MB
print("File size in MB: ", fileSize)
func sizeInMB(data: Data) -> String {
let bytes = Double(data.count)
let megabytes = bytes / (1024 * 1024)
return String(format: "%.2f MB", megabytes)
}
获取字符串的大小,改编自@mozahler的答案
if let data = "some string".data(using: .utf8)! {
print("There were \(data.count) bytes")
let bcf = ByteCountFormatter()
bcf.allowedUnits = [.useKB] // optional: restricts the units to MB only
bcf.countStyle = .file
let string = bcf.string(fromByteCount: Int64(data.count))
print("formatted result: \(string)")
}
let dataObject = Data()
print("Size is \(dataObject)")
应该给你:
Size is 0 bytes
.count
将不再是必要的。