这些天掌握Swift,我已经实现了一个字典<类型:任何>在斯威夫特。一切正常,但代码看起来非常难看。我应该把它归咎于语言的年轻人,还是我对它缺乏经验?任何见解都非常赞赏!
步骤1:创建一个符合Hashable的Type包装器(因为Any.Type和AnyClass都没有)
class HashableType : Hashable
{
let type : Any.Type
//Piggybacking String's Hashable implementation
var hashValue : Int
{
return toString( type ).hashValue
}
init( type : Any.Type )
{
self.type = type
}
init( instance: Any )
{
self.type = instance.dynamicType
}
}
//Equatable implementation, wish it could be nested in the class declaration...
func ==( lhs: HashableType, rhs: HashableType )->Bool
{
return lhs.hashValue == rhs.hashValue
}
第2步:真实世界用例 - 注册类型的默认实例
final class DefaultInstances
{
private static var __defaultInstances = [ HashableType: Any ]()
class func registerDefaultInstance( instance: Any ) -> Bool
{
let hashableType = HashableType( instance: instance )
if let defaultInstance = __defaultInstances[ hashableType ]
{
return false
}
__defaultInstances[ hashableType ] = instance
return true
}
// T, T.Type and T.self can all coexist, not a contrived example.
// T.Type: the "cannot explicitly specialize a generic function" compile error is quite a shame here -
// would be much cleaner in C# for example
class func defaultInstance< T >( type: T.Type ) -> T?
{
return __defaultInstances[ HashableType( type: T.self ) ] as? T
// could also work as
// return __defaultInstances[ HashableType( type: type ) ] as? T
}
}
第3步:测试
func TestDefaultInstances()
{
if DefaultInstances.registerDefaultInstance( Int( 2 ) ) == true
{
println( "did register default int." )
}
else
{
if let defaultInt = DefaultInstances.defaultInstance( Int )
{
println( "Already registered Int default instance: \(defaultInt)")
}
}
}