【问题标题】:Initializer for conditional binding must have Optional type, not 'Substring.SubSequence' (aka 'Substring') - swift [duplicate]条件绑定的初始化程序必须具有可选类型,而不是“Substring.SubSequence”(又名“Substring”) - swift [重复]
【发布时间】:2018-07-28 06:36:54
【问题描述】:

我正在做一个小项目。为了避免 nil 值,我使用 if 条件

if let _result = _fullString.suffix(from: startIndex!){
//do something 
}

但它显示错误

条件绑定的初始化器必须是 Optional 类型,而不是 'Substring.SubSequence'(又名'Substring')

【问题讨论】:

  • 拜托,这是 Swift:没有带有前导下划线的 objective-c-ish 变量。

标签: ios swift string


【解决方案1】:

发生是因为后缀函数没有返回任何可选值。这就是导致可选绑定失败的原因。

您可以使用下面的代码直接使用后缀值

let _result = _fullString.suffix(from: startIndex!)

【讨论】:

  • 但有时后缀函数返回nil,如何避免nil?
  • @BestoftheBest String 类只返回非可选的后缀值。所以不需要可选绑定。
猜你喜欢
  • 2019-04-17
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-28
  • 2019-03-11
  • 2017-01-22
  • 2018-03-25
相关资源
最近更新 更多