stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)在Swift中返回Optional

时间:2014-10-14 05:42:47

标签: ios swift

我正在尝试使用Swift解决以下问题:

1)可选吗? 而不是返回" 1%20Market%20Street,%20San%20Francisco,%20CA%2094107"按照我的意愿,为什么以下代码返回"可选(" 1%20Market%20Street,%20San%20Francisco,%20CA%2094107")"

println("\(address.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding))")

2)如何用%2C替换逗号?

3 个答案:

答案 0 :(得分:2)

1)

使用

println("\(address.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)")

注意! - 它提取可选值。

或者

if let str = address.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
    println(str)
}

2)

您可以使用以下内容:

let stringWithCommas = "Hello,World"
let stringWithReplacedCommas = stringWithCommas.stringByReplacingOccurrencesOfString(",", withString: "%2C", options: NSStringCompareOptions.LiteralSearch, range: nil)

答案 1 :(得分:1)

你可以用这个

  let tempString: String? = "1%20Market%20Street,%20San%20Francisco,%20CA%2094107"
if tempString != nil
{
    let newString = tempString!.stringByReplacingOccurrencesOfString(",", withString: "%2C", options: NSStringCompareOptions.LiteralSearch, range: nil)
}

它返回可选项,因为有时这个方法返回nil。

答案 2 :(得分:0)

1.是的,它返回可选值,因为它可以返回nil值,这在Swift中是可选的,可以详细了解可选值的详细信息,请参阅帖子here

var newString = String()

if let optionalString = newString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
{
   newString = "1%20Market%20Street,%20San%20Francisco,%20CA%2094107"
}

// 2. To replace , with %2C 

newString.stringByReplacingOccurrencesOfString(",", withString: "%2C", options: NSStringCompareOptions.LiteralSearch, range: nil)