Apple 的 documentation 和许多 articles 建议您只需调用
String(substring)
即可将子字符串 (string.subsequence) 转换为字符串,事实上这是可行的。
let str = "Hello world"
let hello = str.prefix(5) //create substr
//CREATE STRING FROM SUBSTRING
let hellostr = String(hello) //gives error
但是,当子字符串是可选的时,如下所示,
let str = Optional("Hello world")
let hello = str?.prefix(5) //create substr
//CREATE STRING FROM OPTIONAL SUBSTRING
let hellostr = String(hello) //gives error
我收到错误
"No exact matches in call to initializer "
什么可能导致此错误?
感谢您的任何建议。
您需要解开可选
Substring
,因为您无法直接从可选 String
创建 Substring
。
您需要决定如何处理
nil
的 hello
值,并据此选择适当的选项。
这里有几个选项:
Optional.map
从 String
创建非可选 Substring
,以防可选值具有非零值,并且如果可选值是 nil
,则将 nil
分配给结果/// hellostr will be nil if hello was nil, otherwise it will have a value
// The type of hellostr is Optional<String>
let hellostr = hello.map(String.init)
hellostr
有一个值,你需要提供一个默认值let hellostr = hello.map(String.init) ?? ""
Optional.map
替换为更详细的语法let hellostr: String
if let hello = hello {
hellostr = String(hello)
} else {
hellostr = ""
}