class MyClass {
var lists = Dictionary<String, Any>()
init(){
lists["lobby"] = [Int]()
lists["events"] = [Int]()
lists["missed"] = [Int]()
}
func isInsideList(id: Int, whichList: String) -> Bool{ //whichList could be "lobby", "events", or "missed"
//check if "id" is inside the specified array?
if let theList = lists[whichList] as? Array { //this throws an error
if theList.contains(id) ......
}
}
}
我怎样才能做到这一点?
答案 0 :(得分:1)
func isInsideList(id:Int,whichList:String) - &gt;布尔{
if let theList = lists[whichList] as? [Int] {
if theList.contains(id) {
return true
}
}
return false
}
答案 1 :(得分:0)
如果您可以选择对字典进行类型转换,请执行以下操作:
var lists = Dictionary<String, [Int]>()
lists["lobby"] = [Int]()
lists["events"] = [Int]()
lists["missed"] = [Int]()
func isInsideList(id: Int, whichList: String) -> Bool{
//whichList could be "lobby", "events", or "missed"
//check if "id" is inside the specified array?
if let theList = lists[whichList] {
for (var i = 0; i < theList.count; i++){
if (id == theList[i]){
return true
}
}
}
return false
}
但是,如果您要求您的字典包含可能各种对象的数组,那么您可以执行以下操作:
var anyList = Dictionary<String, Array<AnyObject?>>()
anyList["lobby"] = [String]()
anyList["events"] = [String]()
anyList["missed"] = [String]()
func isInsideAnyList(id: Int, whichList: String) -> Bool{
// Attempt to get the list, if it exists
if let theList = anyList[whichList] {
// Loop through each element of the list
for (var i = 0; i < theList.count; i++){
// Perform type cast checks on each element, not on the array itself
if (String(id) == theList[i] as? String){
return true
}
}
}
return false
}