Dauris Little

  • About
  • Dauris’s Portfolio
  • Blogging Lyf
  • Contact

Swift Has Tuple

Avatar photo
Dauris
Monday, 31 May 2021 / Published in iOS, Programming Languages, Swift

Swift Has Tuple

It is a very common use case where we want to return two values from a method, which can be either of the same data types or can be of different data types. Typically within this case, we would either create various local variables if the method is of the same class and set those variables from the method and consume them in the place where needed or we could create a struct and return that struct object from the method.

This approach works fine but is it worth defining a new struct every time when we return value(s) from a method. As great as that may sound consider this then if you have several methods which also return value(s) but each method returns the value(s) of different data types. I suppose in said case you could create a separate struct for each of the methods but it isn’t practical and comes on just terrible programming.

Got a Solution?

As the title of this article should have implied Swift has a type called Tuple which is used to group various values in a single compound value. Storing or returning two values of the same or different data types is child play for a tuple. here can or cannot be any relation between both the values.

Using Tuple

It is initialized in two ways:

  • unnamed variables
    • where the names are not defined within the tuple and use their position to access it
var tuple = ("football", "basketball")

print(tuple.0)
print(tuple.1)
  • named variables
    • where the names are defined within the tuple and use the names that were defined for them
var tuple = (atk : 2500, def : 2100)

print(tuple.atk)
print(tuple.def)
Tagged under: functional programming, iOS, iOS Development, swift, swift programming

What you can read next

“Structs vs Classes” and using them
Shimmering in Android
Show/Hide On-Screen Keyboard

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Categories

Recent Posts

  • Gesture Controls for Android w/Kotlin

    Incorporating Gesture controls in your android ...
  • Android Rating: In-App Review API

    An app rating and reviews are crucial if you wa...
  • QR Reader in Android w/ Kotlin

    Turn your phone's camera into a QR scanner...
  • Creating Advance Custom Snackbar w/ Kotlin

    Ask 100 different developers about what they fi...
  • “Structs vs Classes” and using them

    This is because it plays a significant role in ...

© 2017. All rights reserved. Designed by Dauris Little

TOP
This site uses tracking cookies to personalize content and ads. AcceptLearn More