在Swift中打印数据的大小(以兆字节为单位)

79

我有一个Data类型的变量fileData,我不知道如何打印它的大小。

以前在NSData中可以打印长度,但使用这种类型无法实现。

在Swift中如何打印Data的大小?


Swift 5.1答案 - Juan Boero
这在Swift 5.4.2上无需更改即可正常工作,没有任何警告或错误。5.1有什么特别之处? - Mozahler
11个回答

148
使用 yourData.count 并除以 1024 * 1024。使用 Alexander 的绝妙建议:
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

1
这对于PDF和PPT文件也很有用。 - Neeraj Joshi
我尝试了这个,但是输出结果是:There were 1675125 bytes ||||| formatted result: 1,7 MB.....为什么这里有逗号? - Mohit Kumar
可能与您的本地设置有关。 - Mozahler

37

如果你的目标是将大小打印到用户界面上,可以使用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)

1
由于楼主似乎对如何从“Data”实例中获取“count”属性感到困惑,也许您应该更新您的答案,使用它来代替硬编码的数字。 - rmaddy
哎呀 - 刚刚注意到你代码里的注释。那不是太明显啊。 - rmaddy
1
如果我要花时间回答OP的问题,我认为期望他们完整阅读答案并不过分。 - Alexander
@rmaddy,我刚刚查了一下,没有NSDimension用于信息存储(字节)。我有什么遗漏吗? - Alexander
不是我的问题。 - Mozahler
显示剩余4条评论

18

您可以使用 Data 对象的 count,而对于 NSData,您仍然可以使用 length


1
计数表示位还是字节? - Mitul Jindal
4
计数表示数据的字节数。 - abdullahselek
@abdullahselek,我在苹果的文档中找不到描述。你找到了吗? - songgeb
@songgeb 我没有检查过,但你可以在 Foundation 中使用 count - abdullahselek

18

Swift 5.1

extension Int {
    var byteSize: String {
        return ByteCountFormatter().string(fromByteCount: Int64(self))
    }
}

用法:

let yourData = Data()
print(yourData.count.byteSize)

6

根据已接受的答案,我创建了一个简单的扩展:

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))
 }}

5

一个快速的扩展,可以将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
    }
}

1
仅作警告,由于本地设置和语言设置,硬编码的逗号和点以及MB字母可能会丢失/错误。最好将字符过滤为仅数字或类似字符。 - Juan Boero

4

在下面的代码中输入文件的URL以获取文件大小(以MB为单位),希望这可以帮助您。

let data = NSData(contentsOf: FILE URL)!
let fileSize = Double(data.count / 1048576) //Convert in to MB
print("File size in MB: ", fileSize)

1
你有Swift 4.2的更新吗?目前,使用它会看到“无法在类型'Data'上使用实例成员'length'”。 - Jonas

1
func sizeInMB(data: Data) -> String {
    let bytes = Double(data.count)
    let megabytes = bytes / (1024 * 1024)
    return String(format: "%.2f MB", megabytes)
}

下面的代码接受一个Data对象作为参数,并计算该Data对象的大小(以兆字节为单位)。然后将该大小作为字符串返回,最多保留2位小数。

0

获取字符串的大小,改编自@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)")
}

0
如果您只想查看字节数,直接打印数据对象即可。
let dataObject = Data()
print("Size is \(dataObject)")

应该给你:

Size is 0 bytes

换句话说,在更新的Swift 3.2或更高版本中,.count将不再是必要的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接