How to use enum, struct, class in Swift

Source: Internet
Author: User

Import Foundation

Print ("Hello, world!")

Let A = 10
var B = 20
var C = a + B;
c = 3000

Overloading: The function name is the same, the function type is different (parameter, return value is different), constitute the overload, call the time, according to the parameters to determine the call that function
Func HelloWorld (a:int)->int {
Return a * 100
}
Func hellowold (a:string)->int {
Return 100
}
Print (Hellowold ("123"))

For loop
Interval 0 ... Ten = [0, ten] 0..<10 = [0, 10)
For I in 0...10 {
Print ("i = \ (i)")
}

1. Enumeration
2. Classes and structures

Defining enumeration values
Enum Direction:string {
Case east = "East"
Case west = "West"
Case nan = "South"
Case Northern = "North"
}

To define a variable to accept an enumeration value
If you assign a variable to an enumeration value once, the next assignment can be used directly. To assign a value
var dir = direction.east
Print (dir)

var dir2 = Dir
dir =. North
Print ("DIR = \ (dir.rawvalue), Dir2 = \ (dir2.rawvalue)")

The original value of the enumeration value
Enum season:int{
Case Spring = 100
Case Snmmer
Case Fall
Case Winter
}

var se = season.spring
RawValue, original value
Print (Se.rawvalue)

The enumeration value is found by the original value of the enumeration value
Let Sea = Season (rawvalue:100)
Print (SEA)

Implicit parsing
If let S = Sea {
Print ("s = \ (s)")
} else {
Print ("Cannot find enumeration value")
}

Enum student:string{
Case Primary = "Primary School"
Case Junior
Case Senior
Case University
}

var stu = Student.primary
Print (                                                                                                                                                                                                                                                                                                                                                                                                                                                          stu.rawvalue)

Let student = Student (rawValue: "Primary School")
Print (student)

If let St = student {
Print ("St = \ (ST)")
} else {
Print ("Cannot find enumeration value")
}


Enum Fourflower:string {
Case Breaking god = "the old"
Case Dragon god = "Dragon God"
Case master = "Parcel Master"
Case Half sheet = "Half Sheet"
}

Let flower = fourflower. Breaking into God. RawValue
Print ("Breaking God \ (Flower)")

Class and struct body
struct person{
var height = 1.8
var weight = 75
var age = 25
}

Instance structure of the body
() is an initialization method of a struct
var broad en = person ()
Print (Guang-en-weight)
Guang. Weight = 90
Print ("Kwong Eun's weight = \ (Guang en weight) KG")


constructor by device
construct = Alloc...init = Initialize
destructor = Dealloc = Release
var Kankan = person (height:178, weight:70, age:23)

Let str = "Kankan height is \ (Kankan. Height), weight is \ (Kankan. Weight)" + ", Age is \ (Kankan)
Print (str)

var li yang = Kangkang
Kankan. Height = 180
Print ("Li yang. Height = \ (li. Height)")

Class
Class student1{
var num = 12345
var name = "Million Treasure"
var goodfriend = "Breaking into God"
}

The system does not automatically add a constructor to the class
var million = Student1 ()
Million. Goodfriend = "Vietnam"
Print (few. Goodfriend)

var Dragon god = Little
Million. Goodfriend = "Xcode"
Print (Dragon God. Goodfriend)

A = B
Value type: After the assignment is completed, B is modified, and a is unchanged. Enumeration values and struct-bodies are value types. Copy-like procedures
Reference type: After the assignment is complete, b modifies, A as B changes, and the class is the reference type. A process similar to retain

Property
Storage properties: Used to store values and values
Computed properties: The value of the computed property is obtained by means of a Get method, which is generally used to handle transactions. Write only GET, this property is read-only; Cannot write only set
Class Animal {
Store Properties
var type = "Elephant"
var weigh = 1000
Calculated properties
var Leg:int {
get {
if type = = "Elephant" {
Return 4
} else if type = = "Bird" {
Return 2
} else {
Return 3
}
}
The Set method requires a new value parameter
Set (NewValue) {
if (newvalue >= 4) {
Print ("Can't Be Human")
} else {
Print ("Could be a person")
}
}
}
}

var per = Animal ()
Per.type = "Old Man"
Print ("Per.leg = \ (Per.leg)")

Per.leg = 10
Print ("Per.leg = \ (Per.leg)")

Practice
1. Define a struct with the name rect
2. Properties include storage properties, X, Y, with, Height calculation properties CenterX, CenterY
3.centerX and CenterY are computed by storage properties
The set methods of 4.centerX and CenterY are calculated based on X/Y and new values, respectively Width/height

struct Rect {

Properties include storage properties, X, Y, with, height
var x = 0.0
var y = 0.0
var width = 0.0
var height = 0.0

When using attributes inside a class, you can omit self.
It is recommended to add self when it comes to the same parameter name and property.

Calculate attribute CenterX, CenterY
var CenterX:D ouble {
get{
CenterX and CenterY are computed by storage properties
return self.x + self.width/2.0
}set{
The set methods of CenterX and CenterY are calculated based on X/Y and new values, respectively Width/height
width = (newvalue-x) * *
}
}


var centery:D ouble {
get{
Return y + height/2.0
}set{
Height = (newvalue-y)
}
}

}


Property Watcher
Class Plant {

var type = "Green Plant" {
Willset (NewType) {
Print ("NewType = \ (newType), current value \ (type)")
} didset (Oldtype) {
Print ("Oldtype = \ (oldtype), current value \ (type)")
}
}

var Hasflower:bool = false {
Willset {
Print ("New value is \ (newvalue), current value is \ (hasflower)")
} didset {
Print ("old value is \ (oldValue), current value is \ (hasflower)")
}
}
}
var Appletree = Plant ()
Appletree.type = "apple tree"
Appletree.hasflower = True


Type property
Class Fruit {
Whether there is skin
static var Hasrind = True
}

Print ("Whether the fruit has skin: \ (fruit.hasrind)")


Method
Class computer{
var brand = "US Emperor conscience"
var price = 6888
Func des (name:string) {
Print ("\ (name) bought" (brand), took ¥\ (price))
}
}
var Compu = computer ()
Compu.des ("Breaking God")

Class Car {
var brand = "Audi"
var color = "BLACK"
Func TYPE (name:string) {
Print ("\ (name) bought the color of the car, brand is \ (brand)")
}
}
var car = car ()
Car. TYPE ("Alien")

Inherited
Defining the Parent class
Class Teacher {
var academic = "Professor"
var offer = 8888
Func teach () {
Print ("one \ (academic) salary is \ (offer)")
}

Methods that are forbidden to be overridden
Final Forbidden keyword to be overridden
Final func Study (bookname:string) {
Print ("some \ (academic), assiduously (bookname)")
}

var Num:int {
get {
Return 100
} set {

}
}


}

Define a subclass
Lecturer
Class Lecturer:teacher {
var industry = "IOS"
Overriding the parent class method
Override overrides the parent class method keyword
Override Func teach () {
Calling the parent class method
Super.teach ()
Print ("engaged in industry is \ (Industry)")
}
}
Let LEC = Lecturer ()
Lec.academic = "Academician of the two chambers"
Lec.teach ()
Lec.study ("<< on Protracted war >>")

overriding properties
To override a storage property as a computed property
Cannot override a computed property as a stored property
Class Childrenteacher:teacher {
Override Var Offer:int {
get{
Return 10000
} set {

}
}
Override var num = 100
}

Structure
In addition to the optional type attribute, you must assign an initial value to each property during construction
Class hero{
var age:int?
var name:string
var equipment = "Golden Cudgel"
var saddlehorse:string
Init () {
name = "Monkey King"
Saddlehorse = "Wings of the Cloud"
}
Customizing a construction method
Init (name:string, equipment:string, saddlehorse:string) {
Self.name = Name
Self.equipment = Equipment
Self.saddlehorse = Saddlehorse
}
}
Let Monkey King = Hero ()
Print (Monkey King. Saddlehorse)
Let da yu = Hero (name: "Dayu", Equipment: Monkey King equipment, Saddlehorse: "11 bus")

Class Film {
var name:string
var price:float
var director:string

Init (name:string, Price:float, director:string) {
Self.name = Name
Self.price = Price
Self.director = Director
}
Func description () {
Print ("movie name \ (name), Price is \ ("), Director is \ (director) ")
}

Traverse Constructor
And OC is not the same thing, OC is the class method
Convenience adding convenience before constructing the method represents the current constructor as a convenience builder
The traversal constructor must call its own specified constructor
Convenience init () {
Self.init (Name: "123", PRICE:22, Director: "Wang Jing")
Name = "123"
Price = 22
Director = "Wang Jing"
}
}

Let Macau three = Film (name: "The three of Macau", Price:33, Director: "Er Dong Sheng")
Print (Macau three. Price)
Macau three. Description ()

Let villain Angel = Film ()
Villain Angel. Description ()

How to use enum, struct, class in Swift

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.