How do I add a tuple to a Swift Array?

后端 未结 8 488
夕颜
夕颜 2021-01-30 03:02

I\'m trying to add a tuple (e.g., 2-item tuple) to an array.

var myStringArray: (String,Int)[]? = nil
myStringArray += (\"One\", 1)

What I\'m g

8条回答
  •  北海茫月
    2021-01-30 03:36

    If you remove the optional, it works fine, otherwise you'll have to do this:

    var myStringArray: (String,Int)[]? = nil
    
    if !myStringArray {
        myStringArray = []
    }
    
    var array = myStringArray!
    array += ("One", 1)
    myStringArray = array
    

    You can never append an empty array, so you'll have to initialize it at some point. You'll see in the overload operator below that we sort of lazy load it to make sure that it is never nil.

    You could condense this into a '+=' operator:

    @assignment func += (inout left: Array<(String, Int)>?, right: (String, Int)) {
    
        if !left {
            left = []
        }
    
        var array = left!
        array.append(right.0, right.1)
        left = array
    
    }
    

    Then call:

    var myStringArray: (String,Int)[]? = nil
    myStringArray += ("one", 1)
    

提交回复
热议问题