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

时间:2017-03-10 15:52:54

标签: ios swift swift3 nsdata

我有一个Data类型的变量fileData,我很难找到如何打印它的大小。

在过去的NSData中,您可以打印长度但不能使用此类型。

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

10 个答案:

答案 0 :(得分:55)

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

答案 1 :(得分:14)

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

答案 2 :(得分:7)

您可以使用count数据对象,但仍然可以将length用于NSData

答案 3 :(得分:6)

Swift 5.1

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

用法:

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

答案 4 :(得分:3)

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

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

答案 5 :(得分:2)

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

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 :(得分:0)

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

答案 7 :(得分:0)

用于将 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
    }
}

答案 8 :(得分:-1)

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

答案 9 :(得分:-1)

如果只想看字节数,直接打印数据对象可以为您提供。

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

应该给你:

Size is 0 bytes

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