swift3.0 中不能直接使用下标数字进行字符串解决,只能使用String.Index来做位置索引,要想实现截取功能首先得获取到String.Index; 下面两段代码获取开头可结尾,获取中间部分参数用Range<Index>即可; 获取结尾两个字符子串: let sessionId = "this is a test" let index = sessionId.index(sessionId.endIndex, offsetBy: -2)
let suffix = sessionId.substring(from: index) 最后结果为:“st” 获取开头字符两个: let sessionId = "this is a test" let index = sessionId.index(sessionId.startIndex, offsetBy: 2)
let prefix = sessionId.substring(to: index) 最后结果为:“th”