The difference between a tuple (tuples), struct (struct), and enumeration (Enums) in Swift

Source: Internet
Author: User

Swift has many ways of storing data, and you can use enumerations ( enums ), tuples ( tuples ), structs ( structs ), classes (), classes in this article we will compare enumerations, tuples, struct-bodies, first from the simplest start-tuples ( tuples ).

Tuple (tuple)

A tuple is a compound value type that consists of multiple values, for example, you can define atuple

let amout=(100,"EUR")

Tuples are useful when you need to return multiple values, and you can use subscripts to access values in tuples, such as. 0,.1 and so on, as follows:

let currency = money.1 // "USD"

If you want to add more information to a tuple, you can also name each element of the tuple:

let money = (amount: 100, currency: "USD")

Now, you can not only pass .1 , but also .currency access element values.

let currency = money.currency // "USD"

If you want to add formatting to the currency, we can do this:

func format(input: (Int,String)) -> String { return "I have \(input.0) \(input.1) in my wallet"}println(format(money)) // This prints "I have 100 USD in my wallet"

Our format method works well in any (int,string) type of tuple.

let mass = (1, "kg")let formatted = format(mass) // "I have 1 kg in my wallet"
struct (struct)

In fact, "I have 1kg in my purse" does not make any sense, therefore, next we introduce another struct type, struct ( struct ) can not only have the tuple similar data storage function, but also can give the struct definition function (is a tuple tuple , can only define non-member function to implement), Let's take a look at the following structural bodies:

struct Money {    let amount: Int let currency: String}let wallet = Money(amount: 100, currency: "USD")

Now that the structure has the same metadata storage function as the tuple, let's add a function to him now.

extension Money {  func format() -> String { return "I have \(self.amount) \(self.currency) in my wallet" }}println(wallet.format())

If we want to mass add a specific type to weight, we can do this:

  struct  Mass {let Quantity: int let unit: Span class= "Hljs-type" >string func format (), string {return " I have \ ( self.quantity) \ (self.unit) in my Backpack. "}}                

Now the Money type has not only a function, but also a definite name, in the latter part of the code, we cannot mass (1,‘kg‘) pass arguments like that. Struct also called Nomial type: Defines the name of the defined type, if the type name of the object is the same type, in the example code above , mass and the objects that were defined for the first time wallet have the same type members, but their types Money Mass are different types. If we call their format function, we will get different results.

Enumeration (Enums)

If you want to store some values together, we can use them depending on the situation tuple or struct , of course, we can, classes but if we encounter special emptying, for example, sometimes we need to select one of the multiple values, for example, let's take a look at the currencies previous code, We use strings string to make money units, what if we allow only known currencies to appear in the code? We can use enum , if we only allow euros,us dollars and yen, we can create a enum type:

enum Currency {   case EUR case USD case YEN}

Now, if we have a Current value of type, we know it is EUR , USD or YEN one of them, but there is no way to indicate that a member represents another specific meaning, or when it has multiple values at the same time. struct enumerations can also define functions.

extension Currency {    func symbol() -> String { switch self { case .EUR: return "€" case .USD: return "$" case .YEN: return "¥" } }}

We can add as needed case , and of course we can define only one member with an actual value for the enumeration:

enum Angle {   case Radian(radians: Double)}

The above is quite a struct: you can add functions, and distinguish between Angle values and double type values, and if necessary, we can add more to it case (enumeration members).

Which one should I use?

Now let's summarize how tuples to choose struct , enums . First, prioritize tuple if it is competent. If there are 2 values they have the same structure (for example: a pair of strings and int), such as a type that wants to be more type-safe, "named", nominal then it should be used struct , for example, you want to differentiate currency and mass Finally, if multiple value mutexes are required (for example, Eur,usd,yen can only select one), the enumeration is used enums .

The difference between a tuple (tuples), struct (struct), and enumeration (Enums) in Swift

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.