How to create an empty array in Swift?

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

    As per Swift 5

        // An array of 'Int' elements
        let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
    
        // An array of 'String' elements
        let streets = ["Albemarle", "Brandywine", "Chesapeake"]
    
        // Shortened forms are preferred
        var emptyDoubles: [Double] = []
    
        // The full type name is also allowed
        var emptyFloats: Array<Float> = Array()
    
    
    0 讨论(0)
  • 2020-11-30 18:05

    you can remove the array content with passing the array index or you can remove all

        var array = [String]()
        print(array)
        array.append("MY NAME")
        print(array)
        array.removeFirst()
        print(array)
        array.append("MY NAME")
        array.removeLast()
        array.append("MY NAME1")
        array.append("MY NAME2")
        print(array)
        array.removeAll()
        print(array)
    
    0 讨论(0)
  • 2020-11-30 18:07

    There are 2 major ways to create/intialize an array in swift.

    var myArray = [Double]()
    

    This would create an array of Doubles.

    var myDoubles = [Double](count: 5, repeatedValue: 2.0)
    

    This would create an array of 5 doubles, all initialized with the value of 2.0.

    0 讨论(0)
  • 2020-11-30 18:07

    Compatible with: Xcode 6.0.1+

    You can create an empty array by specifying the Element type of your array in the declaration.

    For example:

    // Shortened forms are preferred
    var emptyDoubles: [Double] = []
    
    // The full type name is also allowed
    var emptyFloats: Array<Float> = Array()
    

    Example from the apple developer page (Array):

    Hope this helps anyone stumbling onto this page.

    0 讨论(0)
  • 2020-11-30 18:09

    You could use

    var firstNames: [String] = []
    
    0 讨论(0)
  • 2020-11-30 18:09

    Swift 5

    There are three (3) ways to create a empty array in Swift and shorthand syntax way is always preferred.

    Method 1: Shorthand Syntax

    var arr = [Int]()
    

    Method 2: Array Initializer

    var arr = Array<Int>()
    

    Method 3: Array with an Array Literal

    var arr:[Int] = []
    

    Method 4: Credit goes to @BallpointBen

    var arr:Array<Int> = []
    
    0 讨论(0)
提交回复
热议问题