Skip to content

Instantly share code, notes, and snippets.

@cxa
Last active August 29, 2015 14:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cxa/226a07fa8aad9335c2fb to your computer and use it in GitHub Desktop.
Save cxa/226a07fa8aad9335c2fb to your computer and use it in GitHub Desktop.
Keyboard Layout Model with Swift
enum ShiftKeyType {
case None
case Once
case Always
}
enum PunctuationSwitcherType {
case More
case Numeric
}
enum KeyboardSwitcherType {
case NumericAndPunctuation
case Alphabet
}
enum FunctionKey {
case Shift(ShiftKeyType)
case Delete
case Return
case KeyboardTypeSwitcher(KeyboardSwitcherType)
case InputModeSwitcher
case PunctuationSwitcher(PunctuationSwitcherType)
}
enum Key {
case Character(String)
case Function(FunctionKey)
}
enum KeyboardType {
case Alphabet
case NumericAndPunctutation
case MorePunctutation
}
typealias KeyGroup = [Key]
struct Keyboard {
let type: KeyboardType
let shiftKey: ShiftKeyType
let keyboardSwitcher: KeyboardSwitcherType
let punctuationSwitcher: PunctuationSwitcherType
var keys: [KeyGroup] {
switch (type) {
case .Alphabet:
return [
_mapStrToKeyGroup("QWERTYUIOP"),
_mapStrToKeyGroup("ASDFGHJKL"),
[Key.Function(FunctionKey.Shift(shiftKey))] + _mapStrToKeyGroup("ZXCVBNM") + [Key.Function(FunctionKey.Delete)],
_lastKeyGroup
]
case .NumericAndPunctutation:
return [
_mapStrToKeyGroup("1234567890"),
_mapStrToKeyGroup("-/:;()$&@\""),
_thirdGroupForNonAlphabetKeyboard,
_lastKeyGroup
]
case .MorePunctutation:
return [
_mapStrToKeyGroup("[]{}#%^*+="),
_mapStrToKeyGroup("_\\|~<>€£¥"),
_thirdGroupForNonAlphabetKeyboard,
_lastKeyGroup
]
}
}
private var _lastKeyGroup: KeyGroup {
return [
Key.Function(FunctionKey.KeyboardTypeSwitcher(keyboardSwitcher)),
Key.Function(FunctionKey.InputModeSwitcher),
Key.Character(" "),
Key.Function(FunctionKey.Return)
]
}
private var _thirdGroupForNonAlphabetKeyboard: KeyGroup {
return [Key.Function(FunctionKey.PunctuationSwitcher(punctuationSwitcher))] +
_mapStrToKeyGroup(".,?!'") +
[Key.Function(FunctionKey.Delete)]
}
private func _mapStrToKeyGroup(str: String) -> KeyGroup {
return map(str) { Key.Character(String($0)) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment