How to create an empty array in Swift?

前端 未结 13 869
耶瑟儿~
耶瑟儿~ 2020-11-30 17:25

I\'m really confused with the ways we create an array in Swift. Could you please tell me how many ways to create an empty array with some detail?

相关标签:
13条回答
  • 2020-11-30 18:28

    Swift 5

    // Create an empty array
    var emptyArray = [String]()
    
    // Add values to array by appending (Adds values as the last element)
    emptyArray.append("Apple")
    emptyArray.append("Oppo")
    
    // Add values to array by inserting (Adds to a specified position of the list)
    emptyArray.insert("Samsung", at: 0)
    
    // Remove elements from an array by index number
    emptyArray.remove(at: 2)
    
    // Remove elements by specifying the element
    if let removeElement = emptyArray.firstIndex(of: "Samsung") {
        emptyArray.remove(at: removeElement)
    }
    

    A similar answer is given but that doesn't work for the latest version of Swift (Swift 5), so here is the updated answer. Hope it helps! :)

    0 讨论(0)
提交回复
热议问题