How to create an empty array in Swift?

前端 未结 13 946
耶瑟儿~
耶瑟儿~ 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:11

    Array in swift is written as **Array < Element > **, where Element is the type of values the array is allowed to store.

    Array can be initialized as :

    let emptyArray = [String]()

    It shows that its an array of type string

    The type of the emptyArray variable is inferred to be [String] from the type of the initializer.

    For Creating the array of type string with elements

    var groceryList: [String] = ["Eggs", "Milk"]

    groceryList has been initialized with two items

    The groceryList variable is declared as “an array of string values”, written as [String]. This particular array has specified a value type of String, it is allowed to store String values only.

    There are various properities of array like :

    - To check if array has elements (If array is empty or not)

    isEmpty property( Boolean ) for checking whether the count property is equal to 0:

    if groceryList.isEmpty {
        print("The groceryList list is empty.")
    } else {
        print("The groceryList is not empty.")
    }
    

    - Appending(adding) elements in array

    You can add a new item to the end of an array by calling the array’s append(_:) method:

    groceryList.append("Flour")
    

    groceryList now contains 3 items.

    Alternatively, append an array of one or more compatible items with the addition assignment operator (+=):

    groceryList += ["Baking Powder"]
    

    groceryList now contains 4 items

    groceryList += ["Chocolate Spread", "Cheese", "Peanut Butter"]
    

    groceryList now contains 7 items

提交回复
热议问题