在 Swift 中将可选子字符串转换为字符串

问题描述 投票:0回答:1

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 "

什么可能导致此错误?

感谢您的任何建议。

swift string substring initializer
1个回答
0
投票

您需要解开可选

Substring
,因为您无法直接从可选
String
创建
Substring

您需要决定如何处理

nil
hello
值,并据此选择适当的选项。

这里有几个选项:

  1. 使用
    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)
  1. 如果你总是希望
    hellostr
    有一个值,你需要提供一个默认值
let hellostr = hello.map(String.init) ?? ""
  1. 您还可以使用可选绑定将
    Optional.map
    替换为更详细的语法
let hellostr: String
if let hello = hello {
  hellostr = String(hello)
} else {
  hellostr = ""
}
© www.soinside.com 2019 - 2024. All rights reserved.