Moz*_*ler 67
使用yourData.count并除以1024*1024.使用Alexanders优秀建议:
func stackOverflowAnswer() {
if let data = UIImagePNGRepresentation(#imageLiteral(resourceName: "VanGogh.jpg")) as Data? {
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)")
}
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
There were 28865563 bytes
formatted result: 28.9 MB
Run Code Online (Sandbox Code Playgroud)
Ale*_*ica 15
如果您的目标是打印尺寸以供使用,请使用 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)
Run Code Online (Sandbox Code Playgroud)
Jua*_*ero 11
斯威夫特 5.1
extension Int {
var byteSize: String {
return ByteCountFormatter().string(fromByteCount: Int64(self))
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
let yourData = Data()
print(yourData.count.byteSize)
Run Code Online (Sandbox Code Playgroud)
按照接受的答案,我创建了简单的扩展:
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))
}}
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26080 次 |
最近记录: |