Swift: Test boundary of String.Index for substring function

后端 未结 2 1474
野的像风
野的像风 2021-01-19 02:36

Wow. Swift makes it really fiddly to copy a substring from a simple String.

Most programming languages allow characters to be simply indexed by their intege

2条回答
  •  深忆病人
    2021-01-19 03:00

    I quickly made a nice substring function for Strings without Foundation dependency:

    extension String {
        func substring(from: Int, length: Int) -> String {
            return String(dropFirst(from).prefix(length))
        }
    }
    

    If the length is bigger than possible, it just gives all the characters to the end. Can't crash Can't crash as long as neither argument is negative (it makes sense to crash if any argument is negative since that would be a major flaw in your code).

    Example usage:

    "Stack Overflow".substring(from: 6, length: 12)
    

    gives

    "Overflow"
    

提交回复
热议问题