【问题标题】:Print the size (megabytes) of Data in Swift在 Swift 中打印数据的大小(兆字节)
【发布时间】:2017-08-01 00:59:08
【问题描述】:

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

在过去的 NSData 中,您会打印长度,但无法使用此类型执行此操作。

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

【问题讨论】:

  • 这在 Swift 5.4.2 上没有任何警告或错误。 5.1 有什么特别之处?

标签: ios swift cocoa-touch nsdata foundation


【解决方案1】:

使用 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

【讨论】:

  • 这对于 pdf 和 ppt 文件也很有用。
  • 我试过了,但我得到的输出如下:有 1675125 个字节 |||||格式化结果:1,7 MB .....这里为什么要用逗号?
  • 这可能与您的本地化设置有关。
【解决方案2】:

如果您的目标是打印尺寸以供使用,请使用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)

【讨论】:

  • 由于 OP 似乎对如何从 Data 实例中获取 count 属性感到困惑,也许您应该更新您的答案以使用它而不是硬编码的数字。
  • 糟糕——刚刚注意到代码中的注释。这不是太明显。
  • @rmaddy 如果我要花时间解决 OP 的问题,我认为期望他们实际阅读完整的答案并不是不合理的:p
  • 投了赞成票。我忘记了字节计数格式化程序,尽管我一直在使用它......很好的接触。
  • @rmaddy 我刚刚检查过,没有NSDimmension 用于信息存储(字节)。我错过了什么吗?
【解决方案3】:

你可以使用 count 的 Data 对象,你仍然可以使用 length 的 NSData

【讨论】:

  • count代表位还是字节?
  • Count 代表数据的字节数。
  • @abdullahselek 我在苹果的文档中找不到描述。你呢?
  • @songgeb 我没有检查,但你可以在 Foundation 中 count
【解决方案4】:

斯威夫特 5.1

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

用法:

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

【讨论】:

    【解决方案5】:

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

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

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

      • 你不会认为你有 Swift 4.2 的更新吧?目前,使用它你可以看到“Instance member 'length' cannot be used on type 'Data'”
      【解决方案7】:

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

      【讨论】:

      • 这里只是一个警告,由于区域设置和语言设置、硬编码的逗号和点以及 MB 字母可能丢失/错误。也许最好将字符过滤为仅数字等。
      【解决方案8】:

      如果您只想查看字节数,直接打印数据对象即可。

      let dataObject = Data()
      print("Size is \(dataObject)")
      

      应该给你:

      Size is 0 bytes
      

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

      【讨论】:

        【解决方案9】:

        获取字符串的大小,改编自@mozahler's answer

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

        【讨论】:

          【解决方案10】:

          count 应该适合您的需求。您需要将字节转换为兆字节 (Double(data.count) / pow(1024, 2))

          【讨论】:

          • 存在类型错误:pow 是 (Double, Double) -> Double,但 countInt。您不能将DoubleInt 相乘。
          猜你喜欢
          • 1970-01-01
          • 2010-10-08
          • 2015-02-10
          • 1970-01-01
          • 2011-01-31
          • 1970-01-01
          • 2021-10-01
          • 2021-02-20
          • 2023-03-09
          相关资源
          最近更新 更多