ios - 上下文类型 'String' 不能与数组文字一起使用

标签 ios swift

我在将代码转换为 Swift 3.0 时遇到错误。我的示例代码如下:

func hexRepresentation()->String {

    let dataLength:Int = self.count
    let string = NSMutableString(capacity: dataLength*2)
    let dataBytes:UnsafeRawPointer = (self as NSData).bytes

    for idx in 0..<dataLength {
         string.appendFormat("%02x", [UInt(dataBytes[idx])] as String )
    }

    return string as String
}

最佳答案

该行的作用是:

 string.appendFormat("%02x", [UInt(dataBytes[idx])] as String )

首先,它获取 dataBytes 中索引 idx 处的字节并将其包装在数组中。这是错误消息中引用的数组文字。

接下来,它尝试将数组转换为String - 不是convert:转换。编译器知道这是不可能的,因此会出现错误消息。

幸运的是,您不想将参数转换为字符串,因为您的格式说明符要求 UInt (%x),所以您真正想要的是什么只是

string.appendFormat("%02x", UInt(dataBytes[idx]))

对于获取字节,Swift 类型 Data 有一个函数 foreach这对于迭代字节很方便:

self.forEach { string.appendFormat("%02x", UInt($0)) }

关于ios - 上下文类型 'String' 不能与数组文字一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46274542/

相关文章:

ios - 重建 Realm 数据库

ios - "calinvite"ios 中的 url 方案?

iphone - 安装 Xcode 3.2.4,获取 "Base SDK Missing"

ios - 通过指针地址修改只读 NSData 是否安全?

ios - 尝试在 Swift 中使用 SwiftyJSON 循环时,类型 JSON 不符合协议(protocol) SecuenceType

ios - 将字符串转换为 Int 数组

ios - 在 Info.plist CFBundleSupportedPlatforms 或 modplug 的 Mach-O LC_VERSION_MIN 中找不到平台系列

swift - 使用 JSON、mysql 和 php 的用户注册问题 :EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

swift - 有没有办法在 Swift 包中包含 header

arrays - 如何在 Swift 中打乱数组?