我想创建一个像这样的地图:
val mapCastMethods = Map("Integer" -> toInt)
然后我想调用与地图一起存储的方法。 类似的东西:
"345".mapCastMethods("Integer")
我该怎么做?
答案 0 :(得分:3)
我认为这样的事情应该有效:
do{
guard let entityDic = responseDictionary["Entity"] as? [String: Any] else {return}
guard let servicesDic = entityDic?["Services"] as? [[String:Any]] else {return}
for service in services {
guard let MainServiceCategoryID = service["MainServiceCategories_ID"] as? Int else {return}
MainServiceCategoriesID.append(MainServiceCategoryID)
guard let children = service["Children"] as? [[String:Any]] else {return}
childrenServices.append(children)
if MainServiceCategoryID == 3 {
for child in children {
if let availableService = child["EnglishName"] as? String {
servicesNamesArr.append(availableService)
}
}
}
}
print("childrenServices \(childrenServices)")
} catch let error{
print(error)
}
你应该定义toInt func的函数文字:)
答案 1 :(得分:1)
type Cast[A, X] = A => X
type CastMethods[K, A, X] = Map[K, Cast[A, X]]
implicit def cast[K, A, X](implicit methods: CastMethods[K, A, X]):
K => A => X
= k => a => methods(k)(a)
然后用法:
sealed trait CastMethod
case object Integer extends CastMethod
implicit val methods: CastMethods[CastMethod, String, Int]
= Map(Integer -> (_ : String).toInt)
cast.apply(Integer)("345")