swift 字符串自定义下标截取和赋值

extension String{//字符串截取

    ///读取某个下标字符

    subscript(index:Int)->String{

        get{//读取

            let idx =self.index(self.startIndex, offsetBy: index)

            return String(self[idx])

        }

        set{//修改

            self.remove(at:self.index(self.startIndex, offsetBy: index))

            let new = newValue

            for i in 0..

                let character =Character(new[i])

                let idx =self.index(self.startIndex, offsetBy: index+i)

                self.insert(character, at: idx)

            }

        }

    }

    ///读取闭区间字符串

    subscript(rang: ClosedRange) ->String{

        let range =self.index(startIndex, offsetBy: rang.lowerBound)...self.index(startIndex, offsetBy: rang.upperBound)

        return String(self[range])

    }

    ///读取开区间字符串

    subscript(rang:Range) ->String{

        let range =self.index(startIndex, offsetBy: rang.lowerBound)..

        return String(self[range])

    }

}

你可能感兴趣的:(swift 字符串自定义下标截取和赋值)