查看了网上一些对它们的分析理解,有的地方验证了是错误的。可能是swift版本不同的缘故吧,目前我是使用的swift5。改正一下。
//CountableClosedRange
let rangeA:ClosedRange= (1...5)
// ClosedRange:
let rangeB = (1.1...5.1)
//CountableRange
let rangeC =1..<5
// Range:
let rangeD =1.1..<5.1
print(type(of: rangeA))
print(type(of: rangeB))
print(type(of: rangeC))
print(type(of: rangeD))
输出:
ClosedRange<Int>
ClosedRange<Double>
Range<Int>
Range<Double>
有人说ClosedRange和Range不能遍历循环,其实不对,如果把里面的元素换成整数,是同样可以遍历循环的。
swift截取字符串感觉有些麻烦,截取字符串写了个方法,此方法避免下标越界造成崩溃:
func subClosedRange(bound:ClosedRange) ->String{
var lower = bound.lowerBound
var upper = bound.upperBound
if lower > upper {
(lower, upper) = (upper, lower)
}
I fupper >self.count{
upper =self.count
}
let startIndex =self.index(self.startIndex, offsetBy: lower)
let endIndex =self.index(self.startIndex, offsetBy: upper)
return String(self[startIndex...endIndex])
}
如果用range,最后的返回值修改为return String(self[startIndex..<endIndex]).半开区间。
func subString(start:Int, end:Int) ->String{
if start < end && (end - start) <= (self.count- start) {
let startIndex =self.index(self.startIndex, offsetBy: start)
let endIndex =self.index(self.startIndex, offsetBy: end)
return String(self[startIndex..<endIndex])
}
return ""
}
func subString(from:Int) ->String{
if from >=self.count{
return ""
}
let startIndex =self.index(self.startIndex, offsetBy: from)
let endIndex =self.endIndex
return String(self[startIndex..<endIndex])
}
/// 根据时间格式获取当前时间的字符串
///
/// - Parameter formatter: 时间格式化
/// - Returns: 时间字符串
static func getCurrentTime(formatter:String) ->String{
let date =Date()
let dateFormatter =DateFormatter()
dateFormatter.locale=Locale.current
dateFormatter.dateFormat= formatter
return dateFormatter.string(from: date)
}
网友评论