Swift4 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range upt

前端之家收集整理的这篇文章主要介绍了Swift4 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range upt前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

解决Swift4 substring deprecated: Please use String slicing subscript with a ‘partial range upto’ operator.

extension String {
    func substring(from: Int?,to: Int?) -> String {
        if let start = from {
            guard start < self.characters.count else {
 return ""
            }
        }

        if let end = to {
            guard end >= 0 else {
 return ""
            }
        }

        if let start = from,let end = to {
            guard end - start >= 0 else {
 return ""
            }
        }

        let startIndex: String.Index
        if let start = from,start >= 0 {
            startIndex = self.index(self.startIndex,offsetBy: start)
        } else {
            startIndex = self.startIndex
        }

        let endIndex: String.Index
        if let end = to,end >= 0,end < self.characters.count {
            endIndex = self.index(self.startIndex,offsetBy: end + 1)
        } else {
            endIndex = self.endIndex
        }
 return String(self[startIndex ..< endIndex])
    }

    func substring(from: Int) -> String {
 return self.substring(from: from,to: nil)
    }

    func substring(to: Int) -> String {
 return self.substring(from: nil,to: to)
    }

    func substring(from: Int?,length: Int) -> String {
        guard length > 0 else {
 return ""
        }

        let end: Int
        if let start = from,start > 0 {
            end = start + length - 1
        } else {
            end = length - 1
        }
 return self.substring(from: from,to: end)
    }

    func substring(length: Int,to: Int?) -> String {
        guard let end = to,end > 0,length > 0 else {
 return ""
        }

        let start: Int
        if let end = to,end - length > 0 {
            start = end - length + 1
        } else {
            start = 0
        }
 return self.substring(from: start,to: to)
    }
}
let string = "Hello,World!"
string.substring(from: 1,to: 7) print: ello,Wo

string.substring(to: 7) print: Hello,Wo

string.substring(from: 3) print: lo,World!

string.substring(from: 1,length: 4) print: ello

string.substring(length: 4,to: 7) print: o,Wo

Updated substring(from: Int?,length: Int) to support starting from zero.
原文链接:https://www.f2er.com/swift/321040.html

猜你在找的Swift相关文章