Swift's explanation of the ten-------------exception handling, type conversion (any and anyobject)

Source: Internet
Author: User

Exception handling, type conversion (Any and AnyObject)
1. Error handling (Exception handling)
Swift provides the first type of error support, including throwing at runtime, catching, transferring, and controlling recoverable errors. In swift, errors are represented by the value of the composite ErrorType protocol. Swift enumeration combines a series of related errors. At the same time, some related values can be associated with errors. therefore

The compiler will automatically implement the corresponding composition for Swift enumeration types that implement the ErrorType protocol

Here is a very simple example.

enum WrongName: ErrorType {
    case NoName
}

Error handling 1. Throw
Add the throws keyword after the method

func doSomeThing (name: String) throws-> String {
    if (name.isEmpty) {
        throw WrongName.NoName
    }
    print ("no error")
    return name
}

When the character is empty, we throw this exception.
When calling a throw function, you need to add try before the call

try doSomeThing ("eat") // No exception occurs here, no error will be output

try doSomeThing ("") // runtime error will be generated error caught in main ()

An error is thrown here but not handled.

2. Catching and handling errors do-catch statements to catch and handle errors

Syntax:

do {

} catch parttern {

}

If an error is exploded, the error will be passed to the external domain until it is caught and processed by the catch. The pattern is used to match the error and the corresponding execution statement.

Swift handles exceptions unlike other languages, Swift does not expand the call stack. That will bring a lot of performance loss. The performance of throw statements in swift is almost the same as return

do {
    try doSomeThing ("")
} catch WrongName.NoName {
    print ("NoName error!")
} // Output NoName error!

Use try! To call the throwing function or method to prohibit error transmission. And wrap the call to assert at runtime, so that no errors are thrown. If the frame throws an error, a runtime error will be triggered

func willThrowIfTru (value: Bool) throws {
    if value {
        throw NotTrue.BeTrue
    }
}

do {
    try willThrowIfTru (true)
} catch {
    print ("Cannot be true")
}
// The output here can't be true-no doubt

try! willThrowIfTru (false) // This block prohibits erroneous transmission. It means that there will be no abnormality in the assertion.
1
Finishing operation

Statements executed using defer are executed back to whether there are errors or not. Equivalent to other finally

The execution order of the defer statement sum is opposite to the order in which it is defined. That is to say, the substitution in the first difer statement is executed after the second.

    func willThrowIfTru1 (value: Bool) throws {

        if value {
            throw NotTrue.BeTrue
        }
    }
  do {
            try willThrowIfTru1 (true)
        } catch {
            print ("Cannot be true")
        }


        defer {
            print ("I execute later")
        }

        defer {
            print ("I execute first")
        }
        print ("My first execution")
        result:
        Can't be true
        My first implementation
        I execute first
        I execute

2. Type conversion
Swift is implemented using the is and as operators. These two operators provide a simple and easy way to check the value type or convert it

Use the type check operator (is) to check whether an instance belongs to a specific subtype
class Person {
    var name: String
    init (name: String) {

        self.name = name
    }
}

var p = Person (name: "wangwu")
if p is Person
{
    print ("yes")
}

The output is yes here, and the conversion is obviously meaningless. Take a look at the following,


class Student: Person {

}
class Teacher: Person {

}

let list = [Student (name: "张三"), Student (name: "李四"), Teacher (name: "王 五")]

Here it will be inferred that it is a [Person] array

var stuCount = 0
var teaCount = 0

for item in list {

    if item is Student {
        stuCount ++
    }
    if item is Teacher {
        teaCount ++
    }
}

print ("stu: \ (stuCount), tea: \ (teaCount)")
// stu: 2, tea: 1
1
2
Here is is used to infer the specific type

Down transition
A constant or variable of a certain type may actually belong to a subclass behind the scenes. At this time, you can try to downcast with as! Or as? Downcast may fail. as? returns the optional value you are trying to transform. as! Force transformation, use it when you are very sure, otherwise it will run-time error.
So the above example can be written like this

stuCount = 0
teaCount = 0

// Optional binding is used here, as mentioned in the previous chapter
for item in list {

    if let s = item as? Student {
        stuCount ++
    }
    if let t = item as? Teacher {
        teaCount ++
    }
}

print ("stu: \ (stuCount), tea: \ (teaCount)")
// stu: 2, tea: 1
1
2
The result is exactly the same

Types of Any and AnyObject
Swift provides two special type aliases for uncertain types:
AnyObject can represent an instance of any class type.
Any can represent any type, including function types. (New features in 2.0)
let student: [AnyObject] = [Student (name: "ww"), Student (name: "aa"), Student (name: "dd")]
1
// An array of type [AnyObject] is defined here, but it is sure to be a student, so you can force the transformation
let stu = student [0] as! Student
print (stu.name) // aa
let stus = student as! [Student]
// You can directly cast it to a Student array
print (stus.count) // 3

Let's take a look at the Any type

var things = [Any] ()

things.append ("str")
things.append (0.9)
things.append (stu)
things.append (stus)


for item in things {
    switch item {
    case let val as Double:
        print ("\ (val) is a numeric type")
    case let val as String:
         print ("\ (val) is a string")
    case let val as Student:
        print ("\ (val) is the Student object")
    case let val as [Student]:
        print ("\ (val) is a [Student] array")
    default:
        print ("Nothing is")
    }
}

Results:

str is a string
0.9 is a numeric type
Student is a Student object
[Student, Student, Student] is a [Student] array
Only use these two when you are not sure about the type. It is best to use the certain type when you are sure.

Copyright statement: This article is an original article by bloggers and may not be reproduced without the permission of the bloggers.

Swift detailed explanation ------------- exception handling, type conversion (Any and AnyObject)

label:

Original address: http://www.cnblogs.com/motoyang/p/4783979.html

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.