我有一个数据类型的变量归档,我正在努力寻找如何打印此大小。
在过去的NSDATA中,您将打印长度,但无法使用这种类型进行。
如何在Swift中打印数据的大小?
使用yourdata.count。
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)
您可以使用数据对象的count
,但您仍然可以将length
用于NSDATA
swift 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))
}}
作为 Double
中获得 Data
大小的快速扩展。
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)
如果您只想查看字节数,则直接打印数据对象可以将其提供给您。
let dataObject = Data()
print("Size is (dataObject)")
应该给你:
Size is 0 bytes
换句话说,.count
在较新的Swift 3.2或更高中不需要。
获得字符串的大小,从 @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)")
}
func sizeInMB(data: Data) -> String {
let bytes = Double(data.count)
let megabytes = bytes / (1024 * 1024)
return String(format: "%.2f MB", megabytes)
}
以下内容将Data
对象作为参数,并计算Megabytes中该Data
的大小。然后将大小作为String
返回,最多2个小数点位置。
计数应适合您的需求。您需要将字节转换为Megabytes(Double(data.count) / pow(1024, 2)
)