5.Swift Enumeration | struct | class | attribute | method | Subscript Script | inherit

Source: Internet
Author: User

1. Enumeration:

In Swift, the integer is still applied to indicate the enumeration value, and it needs to be paired with the case keyword

Enum celebrity{Case Dongxie,xidu,nandi,beigai}//left-to-right corresponds to 0,1,2,3

Enum CompassPoint {

Case North

Case South

Case East

Case West

Methods can be defined in enum

Func Show () {

Print (self)

}

}

Defining enum variables

var p = Compasspoint.north

var P2 = Compasspoint.south

P.show ()

P2.show ()

var point:compasspoint =. West

Switch point{

Case. North:

Print ("North")

Case. South:

Print ("South")

Case. East:

Print ("East")

Case. West:

Print ("West")

}

Enum Week:int {

Case Sun, Mon, Tur, Wen, Thu, Fri, Sat

}

The original (bare value) requires a type callout,

Notice: Here the enumeration member is called by invoking the enumeration type Week the Sun bare value (and the enumerated integer value as described in C), the type-marking symbol to be added after the assigned variable

var weekday:int = Week.Sun.rawValue

The current enumeration member can also be invoked directly through the week RawValue method

var week:week? = Week (rawvalue:7)//here if RawValue exceeds the return of the enumeration value, the return is empty, so Week need to use optional values to receive

You can also use the tuple attribute to set the associated enumeration member

Enum BarCode {

Case UIPCA (Int,int,int)//Barcode

Case QRCode (String)//two-D code

}

Defining an enumeration variable

var barcode = BARCODE.UPCA (690,3322323,2)

Barcode = Bar.qrcode ("http://fdsafdsfa.com")

Switch Barcode {

Case BARCODE.UPCA (Let (Num,id,check)):

Print ("This is a barcode \ (num)-\ (ID)-\ (check)")

Case Barcode.qrcode (Let string):

Print ("This is a two-dimensional code corresponding to the string is: \ (String)")

}

}

/** uses a new notation, specifying conditional judgments at the same time as binding variables, similar to sql*/

Switch Apoint {

When binding a variable, you can bind x = = y

Case let (x, y) where x = = y:

Print ("x equals y x = y" on equal Slash)

Case let (x, y) where x = =-Y:

Print ("x and y slash x = y")

Default

Print ("other")

}

2. Structs and classes:

Same point:

Structural problems and classes, all defining a type

Properties and methods can be defined internally

You can define the subscript operator

Can define initialization methods (Int initializer, constructor construction method)

Can be used to extend existing functionality (there are classifications in OC, no classification in Swift, called extensions)

Can follow the established protocol.

Different points:

Classes can inherit, structs cannot

The class is polymorphic and the struct has no

The memory of the class supports automatic reference technology, the struct does not support the reference technology, the struct variable allocates the memory space in the stack, does not need to manage manually

Class is a reference type struct body is a value type

The initialization of a property provides an parameterless and uniform initializer

struct Resolution {

var width = 0.0

var height:float = 0.0

}

class declares that the property must be initialized, unless it is an optional value

Class Videomode {

var resolution = Resolution ()

var interlocaed = False

var framerate = 0.0

var name:string?

}

struct is a value class class is a reference type

var res = Resolution ()

var res2 = Res

Res.width = 1024

Res2.width

var vmode = Videomode ()

var vmode2 = Vmode

Vmode.name = "Zhanshang"

Vmode2.name

/** = = = Compare address Equality */

if Vmode = = = Vmode2 {

Print ("Two references are the same value")

}

If Vmode2!== Vmode {

Print ("Two references are not of the same address")

}

The unified initializer for the/** structure, which is very familiar with the structure problem nesting in C, tightly refers to changing the way variables are defined, and also supports the point syntax to access hierarchical nested properties */

struct Point {

var x:float

var y:float

}

struct Size {

var w:float

var h:float

}

struct Rect {

var origin:point

var size:size

}

var rect = rect (Origin:point (x:100, y:20), Size:size (W:2, H:3))

Rect.size.w

Rect.origin.x

3. Attributes, properties in Swift are categorized in two ways

The first way:

/**

1. There are two ways to categorize properties in Swift

The first way:

Storage attributes (Stored properties): Use variables or constants to save property values

(Calculate properties): calculated.

Example:

Date of birth: storage tree, Age: two time to calculate

The second classification method:

Instance properties and Type properties

*/

Store Properties

struct MyRange {

var location:int

Let Length:int

}

var myrnage = MyRange (location:0, length:100)

struct Point {

var x = 0.0, y = 0.0

}

struct Size {

var w = 0.0, h = 0.0

}

struct Rect {

Store properties, use variables or constants to save stored properties

var orign = point ()//Create point Object

var size = size ()

var Center:point {

get{

Let CenterX = orign.x + SIZE.W * 0.5

Let CenterY = orign.y + size.h * 0.5

Return point (X:centerx, y:centery)//Returns a point type

}

If there are no parameters, use the default NewValue

set{

Let Neworignx = NEWVALUE.X-SIZE.W * 0.5

Let Neworigny = newvalue.y-size.h * 0.5

Orign = Point (X:neworignx, Y:neworigny)//implementation of Origin assignment

}

/* Set (Newcenter) {

Let Neworiginx = NEWCENTER.X-SIZE.W * 0.5

Let Neworiginy = newcenter.y-size.h * 0.5

Origin = Point (X:neworiginx, Y:neworiginy)

} */

Suppose to do a read-only computed property

}

If the computed property is read-only, only one line of code can omit the return

var Center2:point {

get {

Return point (x:500 + 100,y:100)

}

}

}

var rect = rect (Orign:point (x:0, y:0), Size:size (w:300,h:200))

Rect.center.x

Rect.center.y

Rect.center = Point (x:200, y:200)

Rect.orign.x

Rect.orign.y

/** delay properties like OC lazy loading, or deferred loading */

Class Dataimporter {

Init () {

Print ("Dataimporter create")

}

var fileName = "Data.txt"

This needs to be used only to load

}

Class DataManager {

Lazy var dataimporter = Dataimporter ()

}

Create the DataManager object

var DataManager = DataManager ()

/** Add layz*/before the property needs to perform lazy loading

Datamanager.dataimporter

4. Property Monitor: A piece of code that is automatically called when a property changes

--compute properties, deferred properties, cannot set monitor, only storage properties to set monitor

Property monitor, which is not called when the property is initialized

There are two types of property monitor, Willset,didset

Class Stepcounter {

var labelText = "Text content"

/**storeage property*/

var a:int = 10

Read-only computed properties

var B:int {

Return 10

}

Adding Property Monitors to attributes

var totalsteps:int = 10 {

Willset (NewValue) {

Print ("The property will change when called to change to \ (newvalue) is now \ (totalsteps)")

}

didset{

Print ("The property value has changed when the whine is using the original value \ (oldValue) is now \ (totalsteps)")

LabelText = "changed value \ (totalsteps)"

}

}

}

var propertyname:int = 10{Willset (newvalue) {//insercode here} didset{//insertcode here}}

var stepcounter = Stepcounter ()

Stepcounter.totalsteps = 50

Stepcounter.labeltext

Stepcounter.totalsteps = 20

Stepcounter.labeltext

5. Type properties:

In structs or enumerations, properties that use the static adornment and properties that are decorated with the class keyword in the classes are called type properties and are independent of the entire class and object.

A type attribute defined in a struct, either a stored property or a computed property

The type attribute defined in class can only be computed (if you need to use the storage tree seat design type attribute, add the static keyword)

struct Somestrut {

Store Properties

var a = 10

Calculated properties

var B:int {

Return 10

}

Type property

static var x = 10

static Var y:int {

Return 10

}

}

var someStruct1 = Somestrut ()

somestruct1.a//10

var someStruct2 = Somestrut ()

somestruct2.a//10

Somestrut.x//10

Somestrut.y//10

Class SomeClass {

var a = 10

var B:int {

Return 10

}

/** type attribute, too wonderful */

static Var y:int {

Return 100

}

class Var X:int {

Return 100

}

static var Storeageporperty:int = 10//compile pass. Priority use of static

Swift compilation does not pass? class var storageporperty1:int = 100

}

Someclass.y

Someclass.storeageporperty = 123

Someclass.x

6. Example methods, class methods, almost the same as OC

Instance methods and class methods, instance methods in classes are almost the same as OC

instance method of the/** class type */

Class counter{

var count = 0

Func increment () {

count++

}

Func IncrementBy (amount:int) {

Count + = Amount

}

Func IncrementBy (Amount:int, Numberofftimes:int) {

Count + = Amount * Numberofftimes

}

}

/** Create a instance */

var counter = counter ()

/** Invoke Instance method*/

Counter.increment ()

instance method for/** value type */

struct Point {

var x = ten, y = 10//instance value type attribute, called by object, or object self pointer

var z = 250

static var SX = 10//class-type attribute, called by class, or class self pointer

Func Show () {

print ("Dot \ (x)")

POINT.SX = 1111

}

instance method of a value type, the instance property cannot be modified by default, plus mutating if it is not to be modified

mutating func SetX (Px:int,andy y:int) {

x = px

self.x = px

Prevent parameter and attribute names

Self.y = y

POINT.SX = 111

}

}

Enum statusswitch{

Case Study,dining,review,sleep

Func Show () {

Switch self{

Case. Study:

Print ("learning")

Case. Dining:

Print ("Eating Now")

Case. Review:

Print ("reviewing")

Case. Sleep:

Print ("Sleeping")

}

}

/** Toggle State, here if you want to modify self need to add mutating*/in front

mutating func Nextstatus () {

Switch Self {

Case. Study:

Print ("Next meal")

Self =. Dining

Case. Dining:

Print ("Next to Review")

Self =. Review

Case. Review:

Print ("Go to Sleep Next")

Self =. Sleep

Case. Sleep:

Print ("Next to learn")

Self =. Study

}

}

}

var ss = Statusswitch.study

Ss.show ()

Ss.nextstatus ()

Ss.nextstatus ()

Ss.nextstatus ()

Ss.nextstatus ()

Ss.nextstatus ()

Ss.nextstatus ()

Ss.nextstatus ()

Ss.nextstatus ()

7. Type method:

Type method and class method in OC, meaning the same

Class SomeClass {

var prop:int = 0//instance property must have an object to be able to position

class var A:int {//Type property, class can also use the static

Return 10

}

Func Instancemethod () {

Print ("This is a instance method")

Self.prop

Someclass.a

SELF.A A is a class property, so it cannot be called

}

Class Func Typemethod () {///class Func stands for defining a class method

Print ("This is a type method")

Same OC, class method cannot access instance properties, but can access type properties

Self.prop

SELF.A//self The object that calls this method with a table, self equals the object that invokes the class method, the Class object

Someclass.a

}

}

var p = SomeClass ()

P.prop

Someclass.a

Invocation of a class method

Someclass.typemethod ()

First, create a class object-"

var instanceobject = SomeClass ()//class name + () can create an object of a class

Instanceobject.prop

Instanceobject.prop = 10

Instanceobject.prop

struct SomeStruct {

var prop:int = 0

/** declares a static storage property */

static var a:int = 0

Func Show () {}

Func Instancemethod () {

The instance property here can be read but cannot be modified by prop = 1000, if you need to modify the

Self.show ()

Print (prop)

}

In a/** struct, class methods use static, which can be used in classes to define class methods and variable methods in C + +, which is called a static method, but only static in the struct */

static Func Typemethod () {

Print ("This is a type method")

Self.show () instance method,?, cannot be used here

}

}

/** enumeration in the type method */

Enum Statusswitch {

Case Study,dinig,review,sleep

static Func Typemethod () {

Print ("This is a type method")

}

static func Create ()->statusswitch {

return self. Study//statusswitch class calls the Create class method, self points to statusswitch, so returns to the Statusswitch type

}

Func Show () {

Print ("This is an instance method")

}

}

Statusswitch.create (). Show ()//

StatusSwitch.Study.show ()///with the above equivalent//enumeration member can invoke the enumeration class method, so that understanding will be good to remember, do not understand the temporary as a format to remember, and so on the amount of code accumulation went back to study.

8. Subscript script, mainly used to check whether array bounds are out of bounds, how to use assertions

Class MyArray {

Private, cross-border return true, no cross-border return false

pravate var array = [0,1,2,3,4,5,6,7,8,9]

Func indexisvalid (index:int)-bool {

If index < 0 | | Index >array.count-1 {return ture} else {return false}

/** Add Data */

Func Addobjectatindex (Index:int, Object:int) {

ASSERT (Indexisvalid (index))

Array.insert (Object,atindex:index)

}

Func Show () {print (array)}

}

Let the myarray support subscript, the wording of a

Defines a subscript function that constructs an integer by subscript, creates a set and get method, where the NewValue and array assignments in the Set method, the external parameter

Subscript (Index:int)->int {

get {return Array[index]}

set {Array[index] = newvalue}

}

Method Two: By rewriting the Set method

Subscript (index:double)->int {

get{return Array[int (index + 0.5)]}

set{Array[int (index + 0.5)] = newvalue}

Here the NewValue is a set method call when the outer band parameter is similar to (int) Setnewvalue: (int) newvalue

}

var MyArray = MyArray ()

Myarray.show ()

Myarray.addobjectatindex (1, object:100)

Myarray.show ()

Myarray.array + [30,300]

MyArray.array.removeAtIndex (5)

Myarray.show ()

MYARRAY.ARRAY[0]

9. Inheritance:

Parent class Subclass (base class, derived class)

Features in Swift: A class can have no parent class, unlike OC all classes inherit from the Nsobject,swift class, a class can consist of only one parent class, but can have multiple subclasses.

Class Vehicle {

Storage Attributes Storage Properties

var currentspeed = 0.0

Calculate attribute Calculate Properties

var description:string {

Return "Current speed is per hour \ (currentspeed) km"

}

Func makenoise () {

Print ("How the Parent class occurs")

}

Func Show () {

Print ("method shown by the parent class")

}

}

/** inheritance*/

Class Bicycle:vehicle {

/** extension propertie*/

var Hasbasket = False

/** extension method*/

Func Test () {

Print ("Subclass extension method")

}

/** Override Parent method*/

Override Func Makenoise () {

Print ("Subclass Dong Dong ...")

}

}

var bike = Bicycle ()

Bike.show ()

Bike.makenoise ()

Bike.hasbasket

Bike.currentspeed

/** the parent type points to the subtype, before obj is the traffic object, Makenoise overrides, and the subclass method is called first

*/

var obj:vehicle = Bicycle ()

Obj.makenoise ()

}

5.Swift Enumeration | struct | class | attribute | method | Subscript Script | inherit

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.