iOS Learning note 44-swift (iv) Enumerations and structs

Source: Internet
Author: User
Tags mul

First, the enumeration of Swift

enumerations are a common group type associated with a value definition, and allow you to use these values in a type-safe situation when programming.
SwiftThe enumeration in OC is much more powerful than the enumeration in, because Swift the enumeration in is a class-a type, in addition to defining enumeration values, you can define properties and methods in enumerations like classes

1. Simple enumeration definition and use
//定义枚举,使用enum关键字enumMethod{    case Add    case Sub    case Mul    case Div}//可以连在一起写,成员之间用“,“隔开enum CompassPoint {    case North, South, East, West}// 可以使用枚举类型变量或常量接收枚举值,枚举值前有个点var method:Method = .Add// 注意: 如果变量或常量没有指定类型, 那么前面必须加上该值属于哪个枚举类型var point = CompassPoint.North
2. Enumeration and switch statements combine for value matching
method = Method.Sub// 注意: 如果case中包含了所有的值, 可以不写default// 如果case中没有包含枚举中所有的值, 必须写defaultswitch(method){    case Method.Add:        print("加法")    case .Sub:// 如果变量已经指定了枚举类型,可以把前面的枚举类型省略        print("减法")    case .Mul:        print("除法")    case .Div:        print("乘法")    default:        print("都不是")}
3. Original value of the enumeration

OCThe essence of the enumeration in is an integer, so OC the enumeration in the original value, the default is starting from 0, and Swift the enumeration in the default is not the original value, but can be defined when the system let the enumeration has the original value

The enumeration defines the original value:
//define enum type int type, default starting from 0, followed by oneenumCompasspoint:int { CaseNorth, South, East, West}//Defines an enumeration type of type int, starting with the specified value and adding one after theenumMovement:int { Caseleft =5, right, Top, Bottom}//In addition to the int type, Swift enumeration is more powerful and can also be defined as double, string, etc.//But if you specify a different type other than int, you need to assign values to all enumerated valuesenummethod:string { CaseADD ="Add"     CaseSub ="Sub"     CaseMul ="Mul"     CaseDiv ="Div"}enumconstants:double { Caseπ=3.14159     CaseE =2.71828     Caseφ=1.61803398874     Caseλ=1.30357}
Conversion between the enumeration value and the original value:
//Gets the original value corresponding to the enumeration valueprintln("Method.add original value is: \ (Method.Add.rawValue)")//Print: Method.add The original value is: Add/* Create an enumeration value from the original value Note: 1. The original value is case-sensitive 2. Returns an optional type value, because the original value does not necessarily have an enumeration value * /Let method = Method (RawValue:"Add")//Because the return is an optional type, it is possible to nil, preferably using an optional bindingifLet OpE = Method (rawValue:"Sub"){Switch(OpE) { Case. ADD:Print("Addition") Case. Sub:Print("Subtraction") Case. Mul:Print("Division") Case. Div:Print("Multiplication")    }}
4. Enumeration's Associated values

The associated value of an enumeration is an excellent way to attach additional information to an enumeration value. With associative values, each enumeration value can be some specific value in some mode.
For example, you are developing a trading engine that may have "buy" and "sell" two different types of trading. In addition to making a clear stock name and number of trades per lot

The associated value of the enumeration is used
//Define a trade enumerationEnum Tradetmp { CaseBuy (String, Int)//Buy, associate a string and a reshape     CaseSell (String, Int)//Sell, associate a string and a reshape     CaseBorrow (StringIntString)//Borrow, the association type of each enumeration value can be different}//Redefine a trade enumeration and label The associated value with a descriptionEnum Trade { CaseBuy (Stock:String, Amount:int)//Buy, associated stock name and number of trades     CaseSell (Stock:String, Amount:int)//Sell, associated stock name and number of trades}//Create an enumeration that associates certain valuesvarTradebuy = trade.buy (stock:"Baidu", Amount: -)varTradeBuy2 = trade.buy (stock:"APPL", Amount:4000)varTradesell = Trade.sell (stock:"APPL", Amount: +)///The first way to extract the associated value, use the switch statement to extract the associated valueSwitch(tradebuy) { Case. Buy ( LetStock LetAmount): println ("Buy \ (stock) with \ (amount) Number") Case  Let. Sell (stock, amount)://Simplifiedprintln"Sell \ (stock) with \ (amount) Number")}///The second method extracts the associated values, extracts the associated values using pattern matchingif  Case  LetTrade.sell (stock, amount) = Tradesell {println ("Sell \ (amount) of \ (stock)")}
5. Enumeration's Properties

Although adding a storage attribute to the enumeration is not allowed, you can still create a computed property. Of course, the content of the computed attribute is either built under the enumeration value or the enumeration is worth the association.

//定义枚举,添加一个计算属性enum Device {    case iPad, iPhone    var year: Int {        switch self {            casereturn2007            casereturn2010        }    }}//创建一个枚举值var device = Device.iPadprintln("iPad is \(device.year)"//结果:iPad is 2010
6. Methods of Enumeration

The methods in the enumeration are "raw" for each enumeration value. So if you want to execute a particular code in a particular situation, you need to branch or adopt a switch statement to clarify the correct code path.

enumWearable {enumeration can be nested in//enumeration    enumWeight:int { CaseLight =1}enumArmor:int { CaseLight =2}//enumeration value that specifies the type of weight and armor     CaseHelmet (Weight:weight, Armor:armor)//Enumeration methodFunc attributes (), (Weight:int, Armor:int) {SwitchSelf { Case. Helmet ( LetW LetA):return(W.rawvalue *2, A.rawvalue *4)        }    }}//Because both weight and armor have specified enumeration types, use point enumeration values directly LetWearable = Wearable.helmet (weight:. Light, Armor:. Light) LetWoodenhelmetprops = Wearable.attributes () println (Woodenhelmetprops)//Result: (2, 8)

You can also add a static method to an enumeration, in other words, create an enumeration from a non-enumerated type.
In this example, we need to consider the case where the user sometimes calls the Apple device wrong (for example, AppleWatch called iWatch ) and needs to return an appropriate name.

enum Device {    case AppleWatch    //添加静态方法    static func fromSlang(term: String) -> Device? {        if"iWatch" {            return .AppleWatch        }        return nil    }}var device = Device.fromSlang("iWatch"//device为 Device? 类型
Ii. structural body of Swift

In a process-oriented programming language such as C, structs are used much more, but after object-oriented, such as in C++ and OC , structs are seldom used. This is because the structure can do things, the class can be replaced completely.
But the Swift language attaches great importance to the structure, the structure as an important means to achieve object-oriented. There is a big difference between the struct in and and the struct in, and the struct in the structure Swift C++ OC C++ OC can only define a set of related member variables, and the Swift struct in not only define the attributes, but also define the method. Therefore, we can think Swfit of a struct as a lightweight class.

The common place for classes and structs in Swift is:
    • Defining properties for storing values
    • Define methods to provide functionality
    • Define subscript scripts for accessing values
    • Defining constructors for generating initialization values
    • Extended to add functionality to the default implementation
    • Implement protocols to provide some standard functionality
The difference between classes and structs in Swift is:
    • struct has no inheritance
    • Struct does not have run-time coercion type conversions
    • The structure does not have the ability to use the destructor
    • struct does not have the ability to use a reference meter
1. Structure definition
//结构体定义使用struct关键字struct MarkStruct {    //结构体也有存储属性和计算属性,这里只定义了存储属性    var mark1: Int     var mark2: Int    var mark3: Int}//所有结构体都有一个自动生成的成员逐一初始化构造器,用于初始化结构体实例中成员的属性。//顺序必须和结构体成员顺序一致,必须包含所有的成员var marks = MarkStruct(mark1: 98, mark2: 96, mark3:100)println(marks.mark1)println(marks.mark2)println(marks.mark3)
2. struct Definition Properties
structpoint{varx =0.0    vary =0.0}structMyPoint {//define storage properties    varp = Point ()//Define calculation Properties    varpoint:point{Get{returnP}Set(Newpoint) {//Modify newvalue named Newpoint, Nature or NewValuep.x = Newpoint.x p.y = Newpoint.y}}}varp = Point (x:10.0Y:11.0)varMyPoint = MyPoint () Mypoint.point = Pprintln ("X=\ (mypoint.point.x), y=\ (MYPOINT.POINT.Y)")//Running result: x=10.0,y=11.0
3. How to structure the body
//struct The value of the property can be modified only in the constructor (Init), and the value of the inner property of the struct cannot be directly modified within other methods. structRect {varWidth:doublevarHeight:double =0.0    //Define a method for the struct, which belongs to the struct    //The member method in the struct must be called with an instance    //Member method can access member properties    funcGetWidth (), double{returnWidth}}varRect = rect (width:10.0, Height:20.0)//A member method in a struct is bound to an instance object, so who calls, the property that is accessed in the method belongs to whoPrint(Rect.getwidth ())varRect2 = Rect (width:30.0, Height:20.0)//Get Rect2 The width of this objectPrint(Rect2.getwidth ())
4. Value types and reference types

When a value type is assigned to a variable, constant, or itself to a function, it is actually manipulating the copy of the value.
In fact, in Swift , all of the basic types: integers, floating-point numbers, booleans, strings, arrays, and dictionaries are value types and are implemented in the background in the form of structs.
In Swift , all structs and enumerations are value types . This means that their instances, as well as any value type attributes contained in the instance, are copied when passed in the code.

Value type Assignment
structResolution {varwidth =0    varHeight =0}//Create a structLet HD = Resolution (width:1920x1080, Height: the)//struct assignment, actually doing copy operation, cinema and HD structure each occupy separate space in memoryvarCinema = HD//Modify the cinema structure without affecting the HD fabric bodyCinema.width =2048println("Cinema is now \ (cinema.width) pixels wide")//Result: Cinema is now 2048 pixels wideprintln("HD is still \ (hd.width) pixels wide")//Result: HD is still 1920x1080 pixels wide

Unlike value types, a reference type is not copied when it is assigned to a variable, constant, or passed to a function. Therefore, the reference is made to the existing instance itself, not to its copy.
A class is a reference type .

Reference type Assignment
 class resolutionclass {    varwidth =0    varHeight =0Init (Width:int, Height:int) { Self. width = width Self. Height = height}}//Create a Class objectLet Hdclass = Resolutionclass (width:1920x1080, Height: the)//Class object assignment, referencing the same memory spacevarCinemaclass = Hdclass//Modify the Cinema object, and also modify the Hdclass object essentiallyCinemaclass.width =2048println"Cinemaclass is now \ (cinemaclass. width) pixels wide")//Result: Cinema is now 2048 pixels wideprintln"Hdclass is also \ (hdclass.width) pixels wide")//Result: HD is also 2048 pixels wide
5. Selection of classes and structures

struct instances are always passed by value, and class instances are always passed by reference . This means that the two apply different tasks. When you consider the construction and function of a project's data, you need to decide whether each data construct is defined as a class or struct.

Consider building a struct when one or more of the following conditions are met:
    • The main purpose of the structure is to encapsulate a small number of related simple data values.
    • It is reasonable to expect that when an instance of a struct is assigned or passed, the encapsulated data will be copied instead of referenced.
    • Any value type attribute stored in the struct will also be copied, not referenced.
    • Structs do not need to inherit the properties or behaviors of another existing type.
Suitable structural candidates include:
    • Size of geometric shapes
    • Path within a certain range
    • A point within a three-dimensional coordinate system

If you have any questions, please ask in the comments section below! O (∩_∩) o ha!

iOS Learning note 44-swift (iv) Enumerations and structs

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.