Swift 笔记(八)
我的主力博客:半亩方塘
Arrays1、You can declare an array either explicitly or taking advantage of Swift's type inference. Here's an example of an explicit declaration: let numbers: Array<Int> Swift can also infer the type of the array from the type of initializer:
let inferredNumbers = Array<Int>() Another,shorter,way to define an array is by enclosing the type inside square brackets,like so:
let alsoInferredNumbers = [Int]() This isthe most common declaration formfor an array. When you declare an array,you might want to give it initial values. You can do that usingarray literals,which is a concise way to provide array values. An array literal is a list of values separated by commas and surrounded by square brackets: let evenNumbers = [2,4,6,8] It's also possible to create an array with all of its values set to a default value: let allZeros = [Int](count: 5,repeatedValue: 0)
var players = ["Alice","Bob","Cindy","Dan"] print(players.isEmpty) // > false if players.count < 2 { print("We need at least two players!") } else { print("Let's start!") } // > Let's start! var currentPlayer = players.first print(currentPlayer) // > Optional("Alice") print(players.last) // > Optional("Dan") currentPlayer = players.minElement() print(currentPlayer) // > Optional("Alice") print([2,3,1].first) // > Optional(2) print([2,1].minElement()) // > Optional(1) As you might have guessed,arrays also have a Now that you've figured out how to get the first player,you'll announce who that player is: if let currentPlayer = currentPlayer { print("(currentPlayer) will start") } // > Alice will start 3、You can use the subscript syntax with ranges to fetch more than a single value from an array: let upcomingPlayers = players[1...2] print(upcomingPlayers) // >["Bob","Cindy"] As you can see,the constant 4、You can check if there's at least one occurrence of a specific element in an array by using func isPlayerEliminated(playerName: String) -> Bool { if players.contains(playerName) { return false } else { return true } } You could even test for the existence of an element in a specific range:
players[1...3].contains("Bob") // > true 5、You can add Eli to the end of the array using append(_:)
players.append("Eli") You can also append elements using the players += ["Gina"] The right-hand side of this expression is an array with a single element,the string "Gina". 6、You want to add Frank to the list between Eli and Gina. To do that,you can use players.insert("Frank",atIndex: 5) The 7、You can remove the last one in the players list easily with var removedPlayer = players.removeLast() print("(removedPlayer) was removed") // > Gina was removed This method does two things: It removes the last element andthen it returns it,in case you need to print it or store it somewhere else. To remove Cindy from the game,you need to know the exact index where her name is stored. Looking at the list of players,you see that she's third in the list,so her index is 2. removedPlayer = players.removeAtIndex(2) print("(removedPlayer) was removed") // > Cindy was removed How would youget the index of an element? There's a method for that! 8、Frank has decided that everyone should call him Franklin from now on. print(players) // > ["Alice","Eli","Frank"] players[3] = "Franklin" print(players) // > ["Alice","Franklin"]As the game continues,some players are eliminated and new ones come to replace them. Luckily,you can also use subscripting with ranges to update multiple values in a single line of code: players[0...1] = ["Donna","Craig","Brian","Anna"] print(players) // > ["Donna","Anna","Franklin"] 9、If you want to sort the entire array,you should use players = players.sort() print(players) // > ["Anna","Donna",monospace; font-size:1em; border:0px; outline:0px; vertical-align:baseline; background:transparent">sort()does exactly what you expect it to do: It returnsa sorted copyof the array.If you'd like to sort the array in place instead of returning a sorted copy,monospace; font-size:1em; border:0px; outline:0px; vertical-align:baseline; background:transparent">sortInPlace(). let scores = [2,2,8,1,2] let sum = scores.reduce(0,combine: +) print(sum) // > 21 12、 print(scores.filter({ $0 > 5 })) // > [8,6] 13、 map(_:)
also takes a single closure argument. As its name suggests,it maps each value in an array to a new value,using the closure argument.
print(scores) // > [2,2] let newScores = scores.map({ $0 * 2 }) print(newScores) // > [4,16,12,4] With a single line of code,you've created a new array with all the scores multiplied by 2. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |