stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)在Swift中返回Optional
我正在尝试使用Swift解决以下问题:
1)可选? 为什么下面的代码返回“1%20Market%20Street,%20San%20Francisco,%20CA%2094107” “)”
println("\(address.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding))")
2)如何用%2Creplace逗号?
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)
你可以使用这个
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。
1.是返回可选值,因为它可以返回在Swift中可选的nil值来详细了解可选值
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)