6.Swift Protocol | extension | access permissions | exception Debugging | type conversion | arithmetic function | Arc| Class Type Profiler | value type initializer

Source: Internet
Author: User
Tags instance method uikit

1. Protocol (PROTOCOL): The only difference with OC is that the protocol in swift, whether it is a property or a time method, is all that must be done

/** protocol*/

Protocol Fullnamed {

/** computed Properties declaration, read-only computed properties */

var fullname:string {Get}

}

/** Implementation protocol */

struct Person:fullnamed {

The/** implementation protocol allows you to implement a computed property as a stored property, changing the nature of itself */

var fullname:string = "abc"

}

/** in the development of the protocol */

Protocol Mypotocol {

Get set declaration for computed properties

var Prop:int {

Get

Set

}

var onlyread:int{get}

Instance method

Func Instancemethod ()->int

Static methods or class methods

static Func Typemethod ()

}

Class Myclass:mypotocol {

var prop:int = 10

var onlyread:int = 10

Func Instancemethod (), Int {

Return 10

}

Here by specification should write static

Class Func Typemethod () {

Print ("class method")

}

}

var mc = MyClass ()

Mc.prop = 3

Myclass.typemethod ()

Mc.instancemethod ()

Mc.onlyread = 5

Mc.onlyread

Protocol Someprotocol {

Init (A:int)

Func test (), Int

}

Class Parent {

Init (a:int) {}

}

All methods of the protocol in/** Swift must be implemented, where the MyClass need to implement the protocol requires rewriting the method of the parent class, so that both the method and the required protocol are overridden, preceded by the override and required keyword combinations: */

Class Myclass1:parent,someprotocol {

Override Required Init (A:int) {

Super.init (a:100)//Overwrite the internal implementation method is still the parent class method.

}

Func test ()->int {

Return 1

}

}

Using the Protocol method in OC

@objc protocol Objecprotocol {

Func Requiredmethod ()

Optional func Optionalmethod ()

}

Class Objectclass:objecprotocol {

@objc func Requiredmethod () {

}

}

var r2 = Rect (x:100, y:200, w:33, H:2)

2. Extension (Extension), the principle of using extensions in Swift

You can no longer define storage properties in the extension, which is a format that defines an error that cannot be executed

Calculation properties can be defined in a re-extension

Extension double{

You cannot define storage properties in an extension

Error var i = 10

Calculation properties can be defined in the extension

var km:double {

Return self/1000.0

}

var cm:double {

return self * 100.0

}

/** extension A method implementation rounding out */

Func round ()->int{

Integer condition

Return Int (self + 0.5)

}

}

350.0

Print (350.5.km)

Print (350.5.cm)

Print (350.49.round ())

Print (350.50.round ())

struct Point {

var x = 0.0

var y = 0.0

}

struct Size {

var w = 0.0

var h = 0.0

}

struct Rect {

var origin = point ()

var size = size ()

}

var r = Rect ()

By extending an initializer with four parameters, the RECT can assign four values at the time of initialization

Extension Rect {

Init (x:double,y:double, w:double, h:double) {

Self.origin = Point (x:x, y:y)

self.size = Size (w:w, h:h)

}

}

In fact the above operation and OC inside-(ID) Initwithname: (nsstring*) name andage: (int) age{if (self = [super init]; Self.name = name, Self.age = Age)} function is the same, but the form is different.

You can also add methods or calculate value properties by extending the space of the system type

Extension UIButton {

Func Show () {

Print (Self.tag)

}

}

3. Generics (genericity): literal meaning understanding is a widely used type, and overtones can act as many types. And at the time of assignment it will be based on the system's automatic demolition of the company into the type of development (the type of swift language expected)

For example, when I have many different types, it needs to switch values and implement logic.

The function +<t> specifies that T is a generic t that represents various types of

Func swaptwovalues<t> (inout a:t,inout b:t) {

Let temp = a

A = b

b = Temp

}

Swap (&STR1, &STR2)

Str1

str2

/** type array<double belong to a type > */

var arr:array<double> = Array ()

struct Instack {

private var items = [Int] ()

Features of/** Stack LIFO */

mutating func push (Item:int) {

Items.append (item)

}

Mutating func pop (item:int) {

Items.removelast ()

}

}

/**t belongs to a type function, which must be made by the user, using the stack to make T (the type of the elements in the array) */

struct Stack<t> {

private var items = [T] ()//An array of any type, when T is specified why the type, then the array is why type]

/** here uses the specific, LIFO constructs an array */

mutating func push (item:t) {

Items.append (item)

Mutating func pop (item:t) {

Items.removelast ()

}

}

var intstack:stack<int> = Stack ()

var stringstack:stack<string> = Stack ()

4. Access control public means that access is available anywhere

Internal indicates that it is accessible in this project, in order to limit the role threshold of a class member within the scope of the class's action, public is not allowed inside the class

Private functions are accessed in this. xxx file

/** can be accessed anywhere */

public class AClass {

}

/** access in this project */

Internal class IClass {

}

/** limited to this document */

Private class Cclass {

}

/** internal*/

Class Fclass {

The permission for a property cannot be higher than the class public var = c = 2

Internal var a = 10

private var B = 20

}

var fc:fclass = Fclass ()

Fc.a

Fc.b

5. Exception handling: Very useful, especially in the subsequent development and design of user experience related issues. **********************

/** exception Handling (exception), which is a common description of OC, and in our swif provides a class of error support, including runtime throw errors, catch errors, and control recall errors, expressed using a conforming ErrorType protocol.

1. Define error type, generally enumerated value, need to use a value to express the problem in the program

2. Return different ErrorType enumeration values based on different operation results

3. Handling thrown exceptions, usually using the throws{} method to determine the different logical values before calling throw-selective throw error values

4. Handle the thrown exception, take the do {try} Catch enumeration value {}catch enumeration value {}, such a loop to listen for events, continue to try to judge the logic throws an exception, and then execute the receive exception.

*/

error*/of/** Vending machine

Enum Vendingmachineerror:errortype {

Case Invalidselection//no item or selection error, select item Error

Case Outofstock//out of range, not enough

Case Insufficentfounds (required:double)//before enough, how much difference

}

/** Product Entry */

struct Item {

var price:double

var count:int

}

An array of/** goods */

var inventory = ["Cola": Item (price:1.25, count:0), "??": I TEM (price:7.5, Count:3), "??": I TEM (price:0.75, Count:1)]

var amountdeposited = 1.0//Amount

/** throws an exception by condition */

Func vend (itemname:string) throws{

Guard like if, if not empty, jump out of else, guard

Guard var item = Inventory[itemname]

else {

Throw without this product, choose the wrong

Throw Vendingmachineerror.invalidselection

}

Guard Item.count > 0 Else {

Throw Vendingmachineerror.outofstock

}

If amountdeposited >= item.price {

Buy things

amountdeposited-= Item.price

item.count--

}else {

Throw Vendingmachineerror.insufficentfounds (required:item.price-amountdeposited)

}

}

/** Handling Thrown Exception */

do{

Try Vend ("Cola")

}catch vendingmachineerror.invalidselection{

Perform Coke operation when an error occurs, receive, write the reason for the error here

Print ("Select Error")

}catch vendingmachineerror.outofstock{

Print ("Insufficient quantity")

}catch vendingmachineerror.insufficentfounds (let ammoutrequired) {

Print ("Poor \ (ammoutrequired)")

}catch {

Print ("Other unexecption")

}

6. Type conversion:

var d:double = Double (a)

var s:string = "\ (a)"

is as

Media

Class mediaitem{

var name:string

Init (name:string) {

Self.name = Name

}

}

Class Movie:mediaitem {

var director:string//Director

Init (name:string, director:string) {

Self.director = Director

Super.init (Name:name)

}

}

Songs

Class Song:mediaitem {

var singer:string

Init (name:string,singer:string) {

Self.singer = singer

Super.init (Name:name)

}

}

var library: [Mediaitem] = [Song (name: "Jay Chou", Singer: "Blue and white porcelain"), Movie (name: "Charlotte Annoyance", Director: "Curved"), Movie (Name: "Mermaid", dire ctor: "Week Star"), Movie (name: "Avatar", Director: "Love who"), Song (name: "Beijing Beijing", singer: "Wang Feng"), Song (Name: "Legend", Singer: "Li Yu"), Song ( Name: "Father", singer: "Chopsticks brother")]

Write a program to count how many movies multiple fewer songs

var moviecount = 0

var songcount = 0

For item in library {

is to determine if an object is not a type

IsKindOf similar to OC

If Item is Movie {

moviecount++

}

If Item is Song {

songcount++

}

}

It uses polymorphic methods to create a mediaitem type of Libray, which has two types of elements, song and Moview, respectively.

The following we need to determine the type of data to be retrieved from the library.

As? It is possible for a type conversion to succeed and possibly fail to return an optional value

For item in library {

The success of the item into the movie type and assigned to the movie variable, through? Optional values with if else acknowledgment type

If let movie = Item as? Movie {

Print ("Movie Name: \ (movie.name) Director: \ (movie.director)")

}else if let song = Item as? song{

Print ("Song name: \ (song.name) Singer: \ (Song.singer)")

}

}

var m:movie? = Library[4] as? Movie

M?. Name

var m:movie? = Library[4] as? Movie

M?. Name

as! Converted non-selectable value if conversion failed error

var M2:movie = library[2] as! Movie

M2.name

For item in library {

is to determine if an object is not a type

IsKindOf similar to OC

If Item is Movie {

Can get into if hundred percent is a movie object

Let M = Item as! Movie

M.name

M.director

}

If Item is Song {

Let S = Item as! Song

}

}

Know

Any type swift and all types in OC

The Anyobject type is in the OC ID type NSObject, so that we can still print out the program without knowing its type, and avoid errors.

var Nsarray = Nsarray (objects: "abc", "BCD", "Def")

var nsArray2: [String] = Nsarray as! [String]

var nsArray3: [String]? = Nsarray as? [String]

var nsarray4:any = Nsarray as! [String]

var nsarray5:anyobject? = Nsarray as? [String]

7. Operator function: Gu Mings, is to use operator block as a function

operator functions

Func + (A:int, b:int), Int {

Print ("+ number operator function")

Return 100

//}

var x = 100

var y = 200

var z = x + y

Fractional class

Func + (F:fraction, f2:fraction), fraction {

Let n = f.numberator * f2.denominator + f.denominator * f2.numberator

Let d = f.denominator * F2.denominator

return fraction (numberator:n, denominator:d)

}

Write an operator function to support the multiplication of fractions

Func * (F:fraction, f2:fraction), fraction {

Let n = f.numberator * F2.numberator

Let d = f.denominator * F2.denominator

return fraction (numberator:n, denominator:d)

}

struct Fraction {

var numberator:int

var denominator:int

Init (Numberator:int, Denominator:int) {

Self.numberator = Numberator

Self.denominator = Denominator

}

Func Show () {

Print ("\ (numberator)/\ (denominator)")

}

}

var f = fraction (numberator:1, denominator:2)

var F2 = fraction (numberator:1, Denominator:3)

var f3:fraction = f + F2

F3.show ()

var f4 = f * F2

F4.show ()

8. Swift's automatic reference count: Same as OC, no difference

Import UIKit

Class Person {

Let name:string

Init (name:string) {

Self.name = Name

Print ("\ (name) is created")

}

deinit{

Print ("\ (name) is destroyed")

}

}

var Person:person?

var Person2:person?

var Person3:person?

person = person (name: "Zhang San")//Zhang San reference 1

Person2 = person (name: "John Doe")//John Doe reference 1

Person3 = person (name: "Harry")//Harry reference 1

Person3 = person (name: "Guan Yu")

Person3 = nil//Harry reference 0

Person2 = person//John Doe reference 0 three references 2

person = Nil

Person2 = Nil

Class A {

var b:b?

Init () {}

deinit{print ("A is destroyed")}

}

Class B {

No weak is a cyclic strong reference, and B and AClass loop calls

Weak var a:a?

Init () {}

deinit{print ("B is destroyed")}

}

var a:a? = A ()

var b:b? = B ()

Optional chain If A is empty no error will continue

A?. B = b

B?. A = a

A = Nil

b = Nil

9. The class type of the profiler. In fact, it means that the refactoring Init method can assign values directly to a property at the moment it creates the object.

Import UIKit

Class myclass{

The properties in the class must be initialized or initialized in the initializer two places there is a place to initialize without error

var text:string = ""

Optional values are initialized to nil by default

var response:string?

does not provide an initializer with an parameterless default without a single initializer

The system will recycle the default general needs we fill in

Init (text:string) {

Self.text = text

}

}

var mc = MyClass (text: "Test")

Class food{

var name:string

var count = 0

The named constructor that really completes the initialization

Specifies that constructors and convenience constructors can have multiple

Init (name:string) {

Self.name = Name

}

Convenience starter

The convenience initializer will eventually invoke a specified initializer end

Convenience init () {

Name = "Test"

Self.init (Name: "Test")

}

Convenience init (x:D ouble) {

Print (x)

Self.init ()

}

}

Class Apple:food {

var quantity:int

Specifying the initializer

Init (name:string,quantity:int) {

Initialize Subclass Properties First

self.quantity = Quantity

Call the property initializer of the parent class again

Super.init (Name:name)

Copy of the parent class property must be written after the parent class initializer

Self.name = "ABC"

}

Write a handy initializer with a string parameter

Override convenience init (name:string) {

Self.init (Name:name, Quantity:10)

}

deinit{

Print ("Automatic call on Object destruction")

}

}

6.Swift Protocol | extension | access permissions | exception Debugging | type conversion | arithmetic function | Arc| Class Type Profiler | value type initializer

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.