温馨提示:本文翻译自stackoverflow.com,查看原文请点击:ios - Print the size (megabytes) of Data in Swift
cocoa-touch foundation ios nsdata swift

ios - 在Swift中打印数据的大小(兆字节)

发布于 2020-04-19 12:56:02

我有一个数据类型的变量fileData,我正在努力寻找如何打印它的大小。

在过去的NSData中,您将打印长度,但是无法使用此类型进行打印。

如何在Swift中打印数据的大小?

查看更多

提问者
user2512523
被浏览
17
Mozahler 2017-03-11 12:35

使用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)")
      }
    }

结果如下:

There were 28865563 bytes
formatted result: 28.9 MB