Swift 3可选展开

时间:2017-01-28 11:24:36

标签: swift swift3 optional

我想要一个子字符串,用另一个常量String" _TRALLALA"

分隔

这样做很好:

 if let lb = s2.range(of: "_TRALLALA")?.lowerBound
 { let s3 = url.substring(to: lb)
 // do something  
 }

我想在单曲中表达这一点,如果这样:

 if let s3 =  url.substring(to: s2.range(of: "_TRALLALA")?.lowerBound)
 { // do something   
 }

但我明白了:

Value of optional type String.Index? not unwrapped

如何正确表达

4 个答案:

答案 0 :(得分:3)

map可与可选一起使用以解包该值并使用它,或者如果可选项为nil则返回nil。使用它,您的语句可以这样写:

if let s3 = (s2.range(of: "_TRALLALA")?.lowerBound).map({ url.substring(to: $0) }) {
    // do something
}

或(略短)将lowerBound移至map

之后
if let s3 = s2.range(of: "_TRALLALA").map({ url.substring(to: $0.lowerBound) }) {
    // do something
}

答案 1 :(得分:2)

没有可以执行您想要的本机功能,因此您必须将其包装到函数中:

extension String {
    func substring(delimitedBy: String) -> String? {
        guard let range = self.range(of: delimitedBy) else {
            return nil
        }

        return self.substring(to: range.lowerBound)
    }
}

if let s3 = url.substring(delimitedBy: "_TRALLALA") {
    // ...
}

答案 2 :(得分:1)

var s2 = "Hello, playground"

var url = "some url"


let delimiter  =  "_TRALLALA"
let r  = s2.range(of: delimiter) ?? s2.startIndex..<s2.startIndex // if found nil then assigning empty Range

let s3  = url.substring(to: r.lowerBound)
if s3 != "" {
// do something
}

单行

let s3  = url.substring(to: (s2.range(of: "_TRALLALA") ?? s2.startIndex..<s2.startIndex).lowerBound)
if s3 != "" {
// do something

 }

答案 3 :(得分:1)

if let s3 = s2.range(of: "_TRALLALA").flatMap { url.substring(to: $0.lowerBound) }
{ 
    // do something   
}