WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

Properties and methods of arrays

Arrays are also structs, which means they too have their own methods and properties we can use to query and manipulate the array.

Here’s a simple array to get us started:

var toys = ["Woody"]

You can read the number of items in an array using its count property:

print(toys.count)

If you want to add a new item, use the append() method like this:

toys.append("Buzz")

You can locate any item inside an array using its firstIndex() method, like this:

toys.firstIndex(of: "Buzz")

That will return 1 because arrays count from 0.

Just like with strings, you can have Swift sort the items of the array alphabetically:

print(toys.sorted())

Finally, if you want to remove an item, use the remove() method like this:

toys.remove(at: 0)

Arrays have lots more properties and methods – try typing toys. to bring up Xcode’s code completion options.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.9/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.