Statically-typed key for Swift.
A design goal of TypedKey is to provide statically typed key-value interface to Cocoa APIs.
let myKey = Key<String, Int>("myKey")
myKey.key // "myKey"
myKey.keyType // `String`
myKey.valueType // `Int`
let userIDKey = StringKey<Int>("userID")
NSUserDefaults.standardUserDefaults().setObject(10, forKey: userIDKey)
NSUserDefaults.standardUserDefaults().objectForKey(userIDKey) // statically typed `Int?`
let userCellIdentifier = StringKey<UserCell>("userCell")
tableView.registerCell(userCellIdentifier)
tableView.dequeueCell(userCellIdentifier) // statically typed `UserCell?`
let photoCellIdentifier = StringKey<PhotoCell>("photoCell")
collection.registerCell(photoCellIdentifier)
collection.dequeueCell(photoCellIdentifier, forIndexPath: ...) // statically typed `PhotoCell?`
Pull requests are welcomed đź’–
To create your custom typed key, you should implement TypedKey
protocol. For example, this is how StringKey
is implemented:
public struct StringKey<Value>: TypedKey {
public typealias KeyType = String
public typealias ValueType = Value
public let key: KeyType
public init(_ key: KeyType) {
self.key = key
}
}
You can make static typing key-value interface with TypedKey. Functions should use generic with type constraint on TypedKey
. A type of the value can be inferred from the generic by using ValueType
.
func set<T: TypedKey>(key: T, value: T.ValueType) {
// do something great
}
A protocol TypedKey
has two type aliases: KeyType
and ValueType
. You can make generic constraints on it.
func set<T: TypedKey where T.KeyType == String, T.ValueType: AnyObject>(key: T, value: T.ValueType) {
// do something great with String key and AnyObject value
}
-
For iOS 8+ projects with CocoaPods:
pod 'TypedKey', '~> 0.1.0'
-
For iOS 8+ projects with Carthage:
github "devxoul/TypedKey" ~> 0.1.0
-
For iOS 7 projects with CocoaSeeds:
github 'devxoul/TypedKey', '0.1.0', :files => 'Sources/*.swift'
-
Using Swift Package Manager:
import PackageDescription let package = Package( name: "MyAwesomeApp", dependencies: [ .Package(url: "https://github.com/devxoul/TypedKey", "0.1.0"), ] )
TypedKey is under MIT license. See the LICENSE file for more info.