UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

What is a tuple?

Example Code Tuples in Swift occupy the space between dictionaries and structures: they hold very specific types of data (like a struct) but can be created on the fly (like dictionaries). They are commonly used to... Read more >>

Tuple splat syntax is deprecated

Article Another feature that has been deprecated is one that has been part of Swift since 2010 (yes, years before it launched). It's been named "the tuple splat", and not many people were using it. It's partly for that reason – although mainly because it introduces all sorts of ambiguities when reading code – that this syntax is being deprecat... Read more >>

What’s the difference between a struct and a tuple?

Article Swift’s tuples let us store several different named values inside a single variable, and a struct does much the same – so what’s the difference, and when should you choose one over the other? When you’r... Read more >>

When should you use an array, a set, or a tuple in Swift?

Article Because arrays, sets, and tuples work in slightly different ways, it’s important to make sure you choose the right one so your data is stored correctly and efficiently. Remember: arrays keep the order and can have duplicates... Read more >>

How to return multiple values from functions

Tutorial ...Name and lastName will exist, we still need to provide default values just in case things aren’t what we expect. Both of these solutions are pretty bad, but Swift has a solution in the form of tuples. Like arrays, dictionaries, and sets, tuples let us put multiple pieces of data into a single variable, but unlike those other options tuples have a fixed size and can have a variety of data ty... Read more >>

Comparing tuples

Article A tuple is simply a comma-separated list of values, where each value may or may not be named. For example: let singer = ("Taylor", "Swift") let alien = ("Justin", "Bieber") In older versions of Swift, y... Read more >>

Tuples

Tutorial Tuples allow you to store several values together in a single value. That might sound like arrays, but tuples are different: You can’t add or remove items from a tuple; they are fixed in size. You ... Read more >>

What is destructuring?

Example Code Destructuring is the practice of pulling a tuple apart into multiple values in a single assignment. For example, consider a trivial function that accepts names in the format “FirstName LastName” and returns a tuple containing the first and... Read more >>

How are tuples different from arrays in Swift?

Article When you’re learning Swift tuples and arrays can seem like they are the same thing, but really they couldn’t be much more different. Both tuples and arrays allow us to hold several values in one variable, but tuples hold a fi... Read more >>

Improved dictionary functionality

Article ...em behave more like you would expect in certain situations. Let's start with a simple example: filtering dictionaries in Swift 3 does not return a new dictionary. Instead, it returns an array of tuples with key/value labels. For example: let cities = ["Shanghai": 24_256_800, "Karachi": 23_500_000, "Beijing": 21_516_000, "Seoul": 9_995_000]; let massiveCities = cities.filter { $0.value > 10_00... Read more >>

Learn essential Swift in one hour

Article ...int(result) If your function contains only a single line of code, you can remove the return keyword: func rollDice() -> Int { Int.random(in: 1...6) } Returning multiple values from functions Tuples store a fixed number of values of specific types, which is a convenient way to return multiple values from a function: func getUser() -> (firstName: String, lastName: String) { (firstName: ... Read more >>

What’s new in Swift 5.7

Article ... print("Name: \(result.1)") print("Age: \(result.2)") } That creates a regex looking for two particular values in some text, and if it finds them both prints them. But notice how the result tuple can reference its matches as .1 and .2, because Swift knows exactly which matches will occur. (In case you were wondering, .0 will return the whole matched string.) In fact, we can go even furth... Read more >>

Regular expressions

Article ... print("Name: \(result.1)") print("Age: \(result.2)") } That creates a regex looking for two particular values in some text, and if it finds them both prints them. But notice how the result tuple can reference its matches as .1 and .2, because Swift knows exactly which matches will occur. (In case you were wondering, .0 will return the whole matched string.) In fact, we can go even furth... Read more >>

How to calculate the point where two lines intersect

Example Code Finding where two lines cross can be done by calculating their cross product. The code below returns an optional tuple containing the X and Y intersection points, or nil if they don’t cross at all. Note: Core Graphics doesn’t give us a CGLine type, so you’ll need pass this four points: where the first line... Read more >>

Composing views to create a list row

Example Code ... our method – not two different views, and certainly not no views at all. When you try and return two views like this, Swift automatically wraps them up in a single, hidden container called a tuple view, but without any further instructions on how to display this SwiftUI just picks the first view. To fix this we need to put those two views inside a container, which in our case will be a HS... Read more >>

How to find similar words for a search term

Example Code ... a given string by calling its neighbors(for:maximumCount:) method, like this: let similarWords = embedding?.neighbors(for: "rain", maximumCount: 10) That will set similarWords to be an array of tuples, where each tuple contains two values: a word that is similar, and a distance from your original word. This array is sorted by distance, so closest words come first. We asked for “rain”, so... Read more >>

How to rotate a view in 3D

Example Code SwiftUI’s rotation3DEffect() modifier lets us rotate views in 3D space to create beautiful effects in almost no code. It accepts two parameters: what angle to rotate (in degrees or radians), plus a tuple containing the X, Y, and Z axis around which to perform the rotation. Important: If you’ve never done 3D rotation before you should think about the X/Y/Z axes as being skewers through your vie... Read more >>

How to use typealias to make it easier to use complex types

Example Code Although it’s generally a good idea to use structs or classes for defining your types, sometimes you’ll find yourself using tuples. If this happens to you, it’s quite tedious having to type the full definition of your tuple whenever you want to use it, so the typealias lets you create a specific name for it: typealias Na... Read more >>

How to read the red, green, blue, and alpha color components from a UIColor

Example Code ...loat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) return (red, green, blue, alpha) } } Now you can use color.rgba to get back a tuple of all four color values. Read more >>

Key points

Guide ...ven += 1 } else { // this must be odd; add one to our odd count odd += 1 } } // send back our counts as a tuple return (odd, even) } } However, that code won’t work. You see, we’re trying to extend all collections, which means we’re asking Swift to make the method available on arrays lik... Read more >>

How to pass the Fizz Buzz test

Example Code ...ld return “Fizz Buzz”. Otherwise it should return the string form of the input number. There are lots of ways this can be solved in Swift, but I think one of the most interesting is to use tuples like this: func fizzbuzz(number: Int) -> String { switch (number % 3 == 0, number % 5 == 0) { case (true, false): return "Fizz" case (false, true): return "Buzz" ... Read more >>

Summary: Functions

Tutorial ...unction takes less code to write and does the smart thing by default. Functions can return a value if you want, but if you want to return multiple pieces of data from a function you should use a tuple. These hold several named elements, but it’s limited in a way a dictionary is not – you list each element specifically, along with its type. Functions can throw errors: you create an enum d... Read more >>

Arrays vs sets vs tuples

Tutorial Arrays, sets, and tuples can seem similar at first, but they have distinct uses. To help you know which to use, here are some rules. If you need a specific, fixed collection of related values where each item has a prec... Read more >>

What are the changes in Swift 2.2?

Example Code Swift 2.2 introduced a lot of major language changes. You can read my full article explaining the changes with code examples by clicking here, but here are the highlights: You can now compare tuples up to arity 6 Compile-time Swift version checking More keywords can be used as argument labels Renamed debug identifiers: #line, #function, #file The ++ and -- operators are deprecated Traditio... Read more >>

Why are Swift’s closure parameters inside the braces?

Article ...y itself. Closures take their parameters inside the brace to avoid confusing Swift: if we had written let payment = (user: String, amount: Int) then it would look like we were trying to create a tuple, not a closure, which would be strange. If you think about it, having the parameters inside the braces also neatly captures the way that whole thing is one block of data stored inside the variab... Read more >>

10 Quick Swift Tips

Article ...We could decide whether a student passed their course by checking whether all their exam results were 85 or higher: let passed = scores.allSatisfy { $0 >= 85 } 4. Use destructuring to manipulate tuples Destructuring is the ability to pull apart tuples into individual values so you can manipulate them more easily. For example, you might want to call a function like this one: func getCredential... Read more >>

Sending and receiving Codable data with URLSession and SwiftUI

Project ... to the URLSession class, which you can create and configure by hand if you want, but you can also use a shared instance that comes with sensible defaults. The return value from data(from:) is a tuple containing the data at the URL and some metadata describing how the request went. We don’t use the metadata, but we do want the URL’s data, hence the underscore – we create a new local co... Read more >>

How can you return two or more values from a function?

Article ...ctions have a single return type, such as Int or String, but that doesn’t mean we can only return a single value. In fact, there are two ways we can send back multiple pieces of data: Using a tuple, such as (name: String, age: Int) Using some sort of collection, such as an array or a dictionary. If you had a hard time understanding why tuples were important, this is a really good example ... Read more >>

How to count element frequencies in an array

Example Code ...can do so by combining the map() method with a Dictionary initializer. First, create an array of items: let items = ["a", "b", "a", "c"] Second, convert that to an array of key-value pairs using tuples, where each value is the number 1: let mappedItems = items.map { ($0, 1) } Finally, create a Dictionary from that tuple array, asking it to add the 1s together every time it finds a duplicate k... Read more >>

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.