簡體   English   中英

如何創建以數組為對象的字典?

[英]How do I create a dictionary with arrays as the object?

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) ......
       }
    }
}

我該如何實現?

func isInsideList(id:Int,whichList:String)->布爾{

if let theList = lists[whichList] as? [Int] {  

  if theList.contains(id) {

        return true
    }
}

return false

}

如果可以選擇對字典進行類型轉換,請執行以下操作:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM