Swift 4 'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

前端 未结 7 2114
情话喂你
情话喂你 2020-12-30 23:59

i\'ve just converted my little app but i\'ve found this error: \'substring(from:)\' is deprecated: Please use String slicing subscript with a \'partial range from\' operator

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-31 00:39

    Most of my strings have A-Za-z and 0-9 content. No need for difficult Index handling. This extension of String is based on the familiar LEFT / MID and RIGHT functions.

    extension String {
    
        // LEFT
        // Returns the specified number of chars from the left of the string
        // let str = "Hello"
        // print(str.left(3))         // Hel
        func left(_ to: Int) -> String {
            return "\(self[.. String {
            return "\(self[self.index(startIndex, offsetBy: self.length-from)...])"
        }
    
        // MID
        // Returns the specified number of chars from the startpoint of the string
        // let str = "Hello"
        // print(str.left(2,amount: 2))         // ll
        func mid(_ from: Int, amount: Int) -> String {
            let x = "\(self[self.index(startIndex, offsetBy: from)...])"
            return x.left(amount)
        }
    }
    

提交回复
热议问题