我正在处理一个小项目,但我遇到了这个错误,我无法在互联网上找到。
这是我的代码:
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...]
这个错误意味着什么,我该如何解决?
答案 0 :(得分:1)
name
和message
不是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)