Immutable/Mutable Collections in Swift

后端 未结 7 1433
不知归路
不知归路 2020-11-29 18:44

I was referring to Apple\'s Swift programming guide for understanding creation of Mutable/ immutable objects(Array, Dictionary, Sets, Data) in Swift language. But I could\'t

7条回答
  •  广开言路
    2020-11-29 19:30

    Swift does not have any drop in replacement for NSArray or the other collection classes in Objective-C.

    There are array and dictionary classes, but it should be noted these are "value" types, compared to NSArray and NSDictionary which are "object" types.

    The difference is subtle but can be very important to avoid edge case bugs.

    In swift, you create an "immutable" array with:

    let hello = ["a", "b", "c"]
    

    And a "mutable" array with:

    var hello = ["a", "b", "c"]
    

    Mutable arrays can be modified just like NSMutableArray:

    var myArray = ["a", "b", "c"]
    
    myArray.append("d") // ["a", "b", "c", "d"]
    

    However you can't pass a mutable array to a function:

    var myArray = ["a", "b", "c"]
    
    func addToArray(myArray: [String]) {
      myArray.append("d") // compile error
    }
    

    But the above code does work with an NSMutableArray:

    var myArray = ["a", "b", "c"] as NSMutableArray
    
    func addToArray(myArray: NSMutableArray) {
      myArray.addObject("d")
    }
    
    addToArray(myArray)
    
    myArray // ["a", "b", "c", "d"]
    

    You can achieve NSMutableArray's behaviour by using an inout method parameter:

    var myArray = ["a", "b", "c"]
    
    func addToArray(inout myArray: [String]) {
      myArray.append("d")
    }
    
    addToArray(&myArray)
    
    myArray // ["a", "b", "c", "d"]
    

    Re-wrote this answer 2015-08-10 to reflect the current Swift behaviour.

提交回复
热议问题