Swift:条件绑定的初始化程序必须具有可选类型,而不是' String.SubSequence' (又名'子串')

时间:2018-02-06 19:34:46

标签: swift

我正在处理一个小项目,但我遇到了这个错误,我无法在互联网上找到。

这是我的代码:

let bufferRecieved = String(bytesNoCopy: buffer, length: length, encoding: .utf8, freeWhenDone: true)
guard let delimiterFirstIndex = bufferRecieved?.index(of: ":")!,
    let name = bufferRecieved![..<delimiterFirstIndex],
    let message = bufferRecieved![delimiterFirstIndex...] else {
    return nil
}

我明白了:

  

条件绑定的初始化程序必须具有可选类型,而不是&#39; String.SubSequence&#39; (又名&#39;子串&#39;)用于两条指令

let name = bufferRecieved![..<delimiterFirstIndex],
let message = bufferRecieved![delimiterFirstIndex...]

这个错误意味着什么,我该如何解决?

1 个答案:

答案 0 :(得分:1)

namemessage不是Optionals,因此不需要它们成为条件绑定的一部分。把它们放在警卫声明之后:

guard let bufferRecieved = String(bytesNoCopy: buffer, length: length, encoding: .utf8, freeWhenDone: true),
    let delimiterFirstIndex = bufferRecieved.index(of: ":") else {
    return nil
}

let name = bufferRecieved[..<delimiterFirstIndex]
let message = bufferRecieved[delimiterFirstIndex...]
use(name, message)