gpt4 book ai didi

swift - 无法将类型 'NSRange'(又名 'NSRange')的值转换为预期参数类型 'Range'(又名 'Range')

转载 作者:可可西里 更新时间:2023-11-01 00:51:16 27 4
gpt4 key购买 nike

我正在尝试实现 Easy Game Center link但我得到这个错误:

Cannot convert value of type 'NSRange' (aka 'NSRange') to expected argument type 'Range<Index>' (aka 'Range<Int>')

代码如下:

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

最佳答案

您通过转换为 NSRange 使它过于复杂。这有效:

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

关于swift - 无法将类型 'NSRange'(又名 'NSRange')的值转换为预期参数类型 'Range<Index>'(又名 'Range<Int>'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38031612/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com