Created
January 25, 2015 03:30
-
-
Save sarah-j-smith/17cb6f2b2e602b840098 to your computer and use it in GitHub Desktop.
Swift String Extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// StringFunctions.swift | |
// Quest | |
// | |
// Created by Sarah Smith on 24/01/2015. | |
// Copyright (c) 2015 Sarah Smith. | |
// MIT License. | |
import Foundation | |
extension String { | |
/** Returns a copy of this string with all non-letter characters replaced by "X" character. This makes the string suitable for use as a URL fragment, and for use as a key in lookups. */ | |
func keySafe() -> String | |
{ | |
var safeStr = "" | |
var fillerChar : UnicodeScalar = "X" | |
let fragmentChars = NSCharacterSet.URLFragmentAllowedCharacterSet() | |
for uc in self.unicodeScalars | |
{ | |
let uchar = uc.value as UTF32Char | |
let safeCh = fragmentChars.longCharacterIsMember(uchar) ? uc : fillerChar | |
safeStr.append(safeCh) | |
} | |
return safeStr | |
} | |
func fragmentEncode() -> String | |
{ | |
if let result = self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet()) | |
{ | |
return result | |
} | |
return "XXXX-COULD-NOT-ENCODE-AS-FRAGMENT-XXXX" | |
} | |
func fragmentDecode() -> String | |
{ | |
if let result = self.stringByRemovingPercentEncoding | |
{ | |
return result | |
} | |
return "XXXX-COULD-NOT-DECODE-AS-FRAGMENT-XXXX" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shows how to iterate a Swift string and use NSCharacter set operations on the elements of it in a Unicode safe way.