Skip to content

Instantly share code, notes, and snippets.

@ian-mcdowell
Created February 10, 2018 07:33
Show Gist options
  • Save ian-mcdowell/e1775035178d8f21dc95f1321c2d5c1b to your computer and use it in GitHub Desktop.
Save ian-mcdowell/e1775035178d8f21dc95f1321c2d5c1b to your computer and use it in GitHub Desktop.
Swift String Issues
import Foundation
var str = "1"
// The startIndex + 1 should equal the end index, which it does
var position = str.index(str.startIndex, offsetBy: 1)
if position == str.endIndex {
print("Yay!")
}
// Now, if I append another character to the string,
// the position will no longer equal the end index, but will be 1 before the end index.
str.append("2")
if position == str.index(str.endIndex, offsetBy: -1) {
print("Okay cool")
}
// So, advancing the position by 1 should result in the end index, right?
let newPosition = str.index(position, offsetBy: 1)
if newPosition == str.endIndex {
print("Great")
}
// But wait, the newPosition did not change at all by calling index(_:offsetBy:)
if newPosition == position {
print("Position did not change :(")
}
// If I advance the position again, then it's equal to the end index.
let finalPosition = str.index(newPosition, offsetBy: 1)
if finalPosition == str.endIndex {
print("Found the end")
}
print()
print("Now for the next demo")
print()
// Here, we create 2 strings, and store their length
let hello = "hello"
let helloLength = hello.count
let world = "world"
let worldLength = world.count
// If we concatenate the a and b, offset resulting startIndex by the sum of their lengths, we get the endIndex.
let a = hello + world
if a.index(a.startIndex, offsetBy: helloLength + worldLength) == a.endIndex {
print("Concatenation first works")
}
// However, if we split this apart, concatenate after retrieving an index, we get a different result.
var b = hello
let bIndex = b.index(b.startIndex, offsetBy: helloLength)
if bIndex == b.endIndex {
print("This will print")
}
b += world
if b.index(bIndex, offsetBy: worldLength) == b.endIndex {
print("This won't print.")
}
@ian-mcdowell
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment