天天看点

Swift - 字符串(String)Q1Q2参考链接

在实际操作字符串中,会遇到很多坑,记录一下别人遇到的坑,避免自己掉进去。

Q1

问题描述

var stack = Array<String>()  
stack.append("2.3")  
let lastElement = stack.popLast()!  
print("Popped last element: \(lastElement)")  
let number = NSNumberFormatter().numberFromString(lastElement)  
print("NSNumber gives us: \(lastElement)")  
let doubleValue = number!.doubleValue  
print("Double value of this element is: \(doubleValue)")      

上述代码在Playground 以及iOS 模拟器中执行结果如下:

Popped last element: 2.3  
NSNumber gives us: 2.3  
Double value of this element is: 2.3      

但是在真机里是这样的:

Popped last element: 2.3  
NSNumber gives us: 2.3  
fatal error: unexpectedly found nil while unwrapping an Optional value  
(lldb)      

所以提问者修改了一行代码:

let doubleValue = number?.doubleValue      

再次执行:

Popped last element: 2.3  
NSNumber gives us: 2.3  
Double value of this element is: nil      

发现解包失败,值为 nil,那么问题出在那里呢?

解答

由junkpile解答:

你的手机所处国家可能对小数分隔符的定义是一个逗号‘,’,而不是句号‘.’

最后提问者现身说法,确实他设置的德国是使用逗号作为小数分隔符的,所以解包失败。

junkpile 还给出了一个小建议:

在需要对数字字符串进行格式化的地方,比如输入数字的用户控件,你就需要显式的指定数字格式的本地化属性。反之在接收用户输入的数字时,你应该判断本地化属性,让一切尽在掌握中。

Q2

问题描述

这个问题在实战中经常被提及,譬如现在有一个字符串URL:https://api.github.com/gists/public?page=2,我需要从中提取出“?page=2”以及“https://api.github.com/gists/public”,将这两个部分存储到两个变量中,如下:

var strBase = "https://api.github.com/gists/public"
var strPage = "?page=2"      

问题解答前了解下小知识:

  • HTTP GET请求中,url 与请求参数之间用?分隔,参数与参数之间是&分隔。

问题解答

思路:显而易见,关注点应该放在?上,解决方式也五花八门,现提供以下几种方式:

  • 方法一
var urlStr = "https://api.github.com/gists/public?page=2"
var strBase:String        // 请求地址
var strPage:String        // 请求参数

if let qIndex = urlStr.characters.indexOf("?") {  //35
// 2
strBase = urlStr.substringToIndex(qIndex)
strPage = urlStr.substringFromIndex(qIndex)
} else {
// 3
strBase = urlStr
strPage = ""
}      
  1. 首先定位到 ? 的 index 索引值。
  2. 请求地址中存在参数(即存在?),那么通过

    substringToIndex

     和 

    substringFromIndex

     获取到两个部分
  3. 请求地址中不存在参数,那么直接传入的地址就是

    strBase

这里的

qIndex

是一个索引值,类型是

String.CharacterView.Index

,修改该值并非是用 

+、-

 操作,而是调用

qIndex.successor()

 取到下一位索引值,使用

qIndex.predecessor()

取到前一位索引值。

对于

substringToIndex(qIndex)

方法,从 urlStr 的 

startIndex(这里是0)

 开始截取直到 

qIndex

;对于

substringFromIndex(qIndex)

 方法,即从 

qIndex

 索引开始直到

endIndex

前面一个索引,为什么这么说?举个例子,“Hello”字符的 startIndex 毫无疑问是等于0,但 endIndex 不是等于4!!而是5!!最后一个字符的后一位!希望大家记住。

  • 方法二

这里是使用了

componentsSeparatedByString

方法,通过?字符将字符串分隔符将原字符串分割成多个部分到数组中。

let parts = urlStr.componentsSeparatedByString("?")
// 1
strBase = parts[0]
// 2
strPage = parts.count >= 2 ? "?" + parts[1] : ""      
  1. 显然这里只有一个 ? 字符,将原字符串分割成两个部分,第一个部分当然是 strBase 喽
  2. 通过数组的count 来判断是否存在请求参数。
  • 方法三

    这里使用了 NSURLComponents 方法:

if let urlCompo = NSURLComponents(string: urlStr) {
strPage = urlCompo.query != nil ? "?" + urlCompo.query! : ""
urlCompo.query = nil
strBase = urlCompo.string!
} else {
fatalError("invalid URL")
}      

参考链接

Q1原文链接

Q2原文链接

转载于:https://www.cnblogs.com/KilinLee/p/5105800.html