Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Why to use tuples if we have Arrays in swift language and How it is different from Structures?

    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 312
    Comment on it


    Hi Readers,

    Before Moving ahead with the Topic,Lets us Briefly have a overlook what actually a Tuple is:

    * In very simple language:

    A tuple is a group of zero or more values represented as one value. For example ("Pen", "50") holds the Product Name and its Price. You can access the inner values using the dot(.) notation followed by the index of the value:

    var product = ("Pen", "50")
    var firstName = person.0 // Pen
    var lastName = person.1 // 50
    

    What we see above are the Tuples with no names.But we can also give names to the tuples . An element name is an identifier followed by a colon(:).

    var person = (productName: "Pen", price: "50")
    var product_Name = person.productName // Pen
    var price = person.price// 50
    

    Now,we can move further and can clear your doubts that Why we use this thing called Tuple if we have Arrays and Structure with us.

    The advantages of using a tuple instead of an array are

    • In tuple we can store multiple types of values, whereas in an array we can only store values of same type .

    • You cannot pass less or more parameters than expected, whereas in an array you can put any number of arguments

    • In tuple if we pass the parameters in the wrong positions, the compiler will detect that, whereas in Array it doesn't happen.

    • In tuple,If we change the number of parameters, or their type the compiler will produce relevant compilation error, whereas In array it is unnoticed.

    • Assignment is easier and more flexible - for example, the return value can be assigned to a tuple:

    Differences Between Tuples and Structs

    • Before using Structs we need to define it.

    • In Structs we cannot match the pattern against their members.

    • Structs allow mutability of members declared as variables if the instance is a variable.

    • Tuples do not allow mutating functions or functions that refer to any of its members.

    • It is not compulsory that tuples will implement Protocols.

    • We can access the members of tuples with their index number, unlike structs.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: