[英]Print the size (megabytes) of Data in Swift
我有一個數據類型的變量 fileData,我正在努力尋找如何打印它的大小。
在過去的 NSData 中,您會打印長度但無法使用此類型執行此操作。
如何打印Swift中數據的大小?
使用 yourData.count 並除以 1024 * 1024。使用 Alexanders 的好建議:
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)
您可以使用 Data 對象的count
,並且仍然可以使用 NSData 的length
斯威夫特 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))
}}
在以下代碼中輸入您的文件 URL 以獲取以 MB 為單位的文件大小,我希望這對您有所幫助。
let data = NSData(contentsOf: FILE URL)!
let fileSize = Double(data.length / 1048576) //Convert in to MB
print("File size in MB: ", fileSize)
如果你只想查看字節數,直接打印數據對象可以給你。
let dataObject = Data()
print("Size is \(dataObject)")
應該給你:
Size is 0 bytes
換句話說,在較新的 Swift 3.2 或更高版本中不需要.count
。
獲取字符串的大小,改編自@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)")
}
用於將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
}
}
func sizeInMB(data: Data) -> String {
let bytes = Double(data.count)
let megabytes = bytes / (1024 * 1024)
return String(format: "%.2f MB", megabytes)
}
以下將Data
object 作為參數並計算該Data
的大小(以兆字節為單位)。 然后將大小作為最多保留 2 位小數的String
返回。
count應該適合您的需求。 您需要將字節轉換為兆字節( Double(data.count) / pow(1024, 2)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.