Skip to content

Implement hasPrefix and hasSuffix in Swift #737

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 47 additions & 2 deletions stdlib/public/core/StringLegacy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,53 @@ extension String {
}
}
#else
// FIXME: Implement hasPrefix and hasSuffix without objc
// rdar://problem/18878343
extension String {
/// Returns `true` iff `self` begins with `prefix`.
func hasPrefix(other:String) -> Bool {
let otherCharacters = other.characters
if otherCharacters.isEmpty { return false }
let otherStart = otherCharacters.startIndex
let otherEnd = otherCharacters.endIndex

let selfCharacters = self.characters
let selfStart = selfCharacters.startIndex
let selfEnd = selfCharacters.endIndex

var s = selfStart
var o = otherStart

while ( s < selfEnd && o < otherEnd ) {
if selfCharacters[s] != otherCharacters[o] { return false }
s = s.successor()
o = o.successor()
}
return o == otherEnd
}

/// Returns `true` iff `self` ends with `suffix`.
func hasSuffix(other:String) -> Bool {
let otherCharacters = other.characters
if otherCharacters.isEmpty { return false }
let otherStart = otherCharacters.startIndex
let otherEnd = otherCharacters.endIndex

let selfCharacters = self.characters
if selfCharacters.isEmpty { return false }
let selfStart = selfCharacters.startIndex
let selfEnd = selfCharacters.endIndex

var s = selfEnd
var o = otherEnd

repeat {
s = s.predecessor()
o = o.predecessor()
if selfCharacters[s] != otherCharacters[o] { return false }
} while ( s > selfStart && o > otherStart )

return o == otherStart
}
}
#endif

// Conversions to string from other types.
Expand Down