Skip to content

Instantly share code, notes, and snippets.

@robtimp
Created May 11, 2015 22:11
Show Gist options
  • Save robtimp/7e4c11348c6c2fcc5203 to your computer and use it in GitHub Desktop.
Save robtimp/7e4c11348c6c2fcc5203 to your computer and use it in GitHub Desktop.
Swift smart quotes
// Light-weight Swift smart quote implementation
// By Rob Hudson
// 5/11/2015
import UIKit
let text = "\"Would you tell me, please, which way I ought to go from here?\" " +
"That depends a good deal on where you want to get to,\" said the Cat. " +
"\"I don’t much care where-\" said Alice. " +
"Then it doesn’t matter which way you go,\" said the Cat. " +
"\"-so long as I get SOMEWHERE,\" Alice added as an explanation. " +
"Oh, you’re sure to do that,\" said the Cat, \"if you only walk long enough.\""
func useSmartQuotes(var string: String) -> String {
string = replaceDumbQuote("'", string: string, leftQuote: "‘", rightQuote: "’")
string = replaceDumbQuote("\"", string: string, leftQuote: "“", rightQuote: "”")
return string
}
private func replaceDumbQuote(dumbQuote: Character, var #string: String, #leftQuote: String, #rightQuote: String) -> String {
var characterSet = NSMutableCharacterSet.whitespaceAndNewlineCharacterSet()
characterSet.addCharactersInString("([{:<=")
while let characterIndex = find(string, dumbQuote) {
let characterPosition = distance(string.startIndex, characterIndex)
var prevChar: unichar
if characterPosition != 0 {
let prev = string[advance(characterIndex, -1)]
prevChar = ("\(prev)" as NSString).characterAtIndex(0)
} else {
prevChar = (" " as NSString).characterAtIndex(0)
}
var smartQuote: String
if characterSet.characterIsMember(prevChar) {
smartQuote = leftQuote
} else {
smartQuote = rightQuote
}
let range = Range(start: advance(characterIndex, 0), end: advance(characterIndex, 1))
string = string.stringByReplacingCharactersInRange(range, withString: smartQuote)
}
return string
}
useSmartQuotes(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment