Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Foundation
extension String {
func isFirstLetters(count: Int, of characterSet: CharacterSet) -> Bool {
guard characters.count >= count else {
return false
}
let firstLetters = substring(to: index(startIndex, offsetBy: count))
let isInSubset = CharacterSet(charactersIn: firstLetters).isSubset(of: characterSet
)
return isInSubset
}
}
extension CharacterSet {
static var vowels: CharacterSet {
return CharacterSet(charactersIn: "AEIOUYaeiouy")
}
}
"abcDEf".isFirstLetters(count: 3, of: .vowels) // false
"aioDEf".isFirstLetters(count: 3, of: .vowels) // true
"abcDEf".isFirstLetters(count: 1, of: .vowels) // true
"bbcDEf".isFirstLetters(count: 1, of: .vowels) // false
"ibcDEf".isFirstLetters(count: 1, of: .vowels) // true
"ABcdef".isFirstLetters(count: 3, of: .uppercaseLetters) // false
"ABDdef".isFirstLetters(count: 3, of: .uppercaseLetters) // true
"abBABcdef".isFirstLetters(count: 3, of: .lowercaseLetters) // false
"abbABDdef".isFirstLetters(count: 3, of: .lowercaseLetters) // true
"ABD".isFirstLetters(count: 3, of: CharacterSet(charactersIn: "A"..."C")) // false
"ABD".isFirstLetters(count: 3, of: CharacterSet(charactersIn: "A"..."D")) // true
// debug info
extension CharacterSet {
var characters: [Character] {
var result: [Character] = []
for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
result.append(Character(uniChar))
}
}
}
return result
}
}
print(CharacterSet.uppercaseLetters.description) //<Foundation._SwiftNSCharacterSet: 0x6000000271a0>
print(String(CharacterSet.vowels.characters)) //AEIOUYaeiouy
print(CharacterSet.vowels.characters) // ["A", "E", "I", "O", "U", "Y", "a", "e", "i", "o", "u", "y"]
@PeeJWeeJ

This comment has been minimized.

Copy link

commented Jan 31, 2017

What I mean is you could do something like this:

func substringIsSubset(of characterSet: CharacterSet, from range: Range<String.Index>) -> Bool {
    guard range.lowerBound >= self.startIndex && range.upperBound <= self.endIndex else {
 	return false
     }
     return CharacterSet(charactersIn: substring(with: range)).isSubset(of: characterSet)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.