Learn from the Geek Academy: Strings and collections in Swift
Tool: Xcode6.4
Directly on the basis of the sample code, more knocks more experience will have a harvest: hundred see not like a knock, a knock will
1 Import Foundation2 3 4 //Arrays : 1, array creation 2, accessing and modifying arrays5 6 /*declaring array notation:7 the first kind: array<sometype>, such as Array<int>8 the second type: [SomeType], such as [String]9 */Ten //First Kind Onevar Myarr = array<string> ()//create an empty array and assign a value to the Myarr variable A println (Myarr) -var num = array<int> (count:3, Repeatedvalue:1) - println (num) the //The second Kind -var arr: [Int] = [1,2,3] - - //use construct syntax to create an empty array of specific data types +var someints =[Int] () -var threedoubles = [Double] (count:3, Repeatedvalue:1.2) +var food = ["Apple","Orange","Tomato","Potato"]//It's more of a way to use. A println (Food.count) atprintln (food[3]) - - -var shoppinglist = ["Eggs",123,true] - //because of the different types of array storage, swift defaults to the Anyobject type when accessing each element - forIteminchshoppinglist{ in println (item) - } to + /*The following program code will give an error because the fruit here is the default let type - For fruit in food{ the fruit = "good" * println (Fruit) $ }Panax Notoginseng */ - /** * * * variable of array * * * **/ the //1.append () method adds a new element at the end of the array +Food.append ("Vegetables:mushroom") A //2. Adding an array of elements via addition theFood + = ["Pineapple","Pitaya"] + println (food) - //3. Replace, specify the subscript range of the substitution, then the given replacement element, $ //There are not enough elements, not enough to become an array of elements, here is not just programming empty elements, but no $food[1...3] = ["A","B"] - println (food) - the /** * * * * The usual method of array * * * **/ -Food.insert ("Meat", Atindex:2)//inserted objects and locationsWuyi println (food) the //use the Removeatindex method to move an item in an array -Food.removeatindex (4) Wu println (food) - //Delete the last element using the Removelast method About food.removelast () $ println (food) - //Delete all elements, parameter is whether to preserve data buffering, default is False -Food.removeall (keepcapacity:false) -println (food)
The result of the operation is:
Arrays in Swift