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

use*_*523 27 nsdata ios swift swift3

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

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

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

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)


abd*_*lek 9

您可以使用countData对象,但您仍然可以使用lengthNSData

  • Count 表示数据的字节数。 (4认同)

Jov*_*vic 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))
 }}
Run Code Online (Sandbox Code Playgroud)


Muh*_*Gül 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
    }
}
Run Code Online (Sandbox Code Playgroud)