无法转换类型的价值&#39; NSRange&#39; (又名&#39; NSRange&#39;)预期参数类型&#39;范围<索引>&#39; (又名&#39;范围<int>&#39;)

时间:2016-06-25 18:22:03

标签: swift swift3 nsrange

我正在尝试实施Easy Game Center link但我收到此错误:

  

无法转换类型的值&#39; NSRange&#39; (又名&#39; NSRange&#39;)预期   参数类型&#39;范围&lt;索引&gt;&#39; (又名&#39;范围&lt; Int&gt;&#39;)

这是代码:

 static func unarchive(_ data: Data!) -> Packet {
    var archivedPacket = ArchivedPacket(index: 0, numberOfPackets: 0, nameLength: 0) //, dataLength: 0
    let archivedStructLength = sizeof(ArchivedPacket)

    let archivedData = data.subdata(in: NSMakeRange(0, archivedStructLength))
    (archivedData as NSData).getBytes(&archivedPacket)

    let nameRange = NSMakeRange(archivedStructLength, Int(archivedPacket.nameLength))
    let nameData = data.subdata(in: nameRange)
    let name = NSString(data: nameData, encoding: String.Encoding.utf8) as! String
    let packet = Packet(name: name, index: archivedPacket.index, numberOfPackets: archivedPacket.numberOfPackets)

    return packet
}

编辑:这是结构的完整代码:

import Foundation
/**
*  Packet
*/
struct Packet {
    var name: String
    var index: Int64
    var numberOfPackets: Int64

    /**
    *  Struc
    */
    struct ArchivedPacket {
        var index : Int64
        var numberOfPackets : Int64
        var nameLength : Int64
    }
    /**
    Archive Packet

    - returns: NSData
    */
    func archive() -> Data {

        var archivedPacket = ArchivedPacket(index: Int64(self.index), numberOfPackets: Int64(self.numberOfPackets), nameLength: Int64(self.name.lengthOfBytes(using: String.Encoding.utf8)))

        let metadata = Data(
            bytes: UnsafePointer<UInt8>(&archivedPacket),
            count: sizeof(ArchivedPacket)
        )

        let archivedData = Data(data: metadata) as Data
        archivedData.append(name.data(using: String.Encoding.utf8, allowLossyConversion: false)!)

        return archivedData
    }
    /**
    Unarchive Packet

    - parameter data: NSData

    - returns: Packet
    */
    static func unarchive(_ data: Data!) -> Packet {
        var archivedPacket = ArchivedPacket(index: 0, numberOfPackets: 0, nameLength: 0) //, dataLength: 0
        let archivedStructLength = sizeof(ArchivedPacket)

        let archivedData = data.subdata(in: NSMakeRange(0, archivedStructLength))
        (archivedData as NSData).getBytes(&archivedPacket)

        let nameRange = NSMakeRange(archivedStructLength, Int(archivedPacket.nameLength))
        let nameData = data.subdata(in: nameRange)
        let name = NSString(data: nameData, encoding: String.Encoding.utf8) as! String
        let packet = Packet(name: name, index: archivedPacket.index, numberOfPackets: archivedPacket.numberOfPackets)

        return packet
    }
}

1 个答案:

答案 0 :(得分:4)

通过转换为NSRange,您过度复杂了。这有效:

let archivedData = data.subdata(in: 0..<archivedStructLength)
let nameData = data.subdata(in: archiveStructLength..<(archiveStructLength + Int(archivedPacket.nameLength)))