Swift Programming authoritative guide 2nd edition read after harvest

Source: Internet
Author: User
Since participating in the work has been using OC to do iOS development. In 2015, Apple just launched swift1.0 soon, then, after all, is the new language, we are also very enthusiastic to learn.  However, after learning to find it difficult to use in the actual project, coupled with the company's projects are based on OC to do the development, put Swift aside. Later also constantly see the online on the various evaluation of SWIFT, there are good and bad, in short, is a newly launched Language bar.  There are some problems with the grammatical design, which is seamlessly linked to OC, and is acceptable. Since Apple introduced swift4.0 in September 2017, the basic grammatical changes have gone. Slowly, many companies are starting to use Swift to develop their company projects.  This also shows that Swift is stable enough to solve the actual project problem. 2018 because of the work change, into the current company. The company's projects are mostly based on swift development, with a small use of OC. This time I felt the need for the system to learn swift. Search on the Internet there is no better swift books. Read a lot of the evaluation found that "the Swift Programming Authority Guide" whether from the entry difficulty or the way of interpretation is very suitable for me. Just pick it up. I saw it on the Kindle. Time is on the commute to the subway and after work break time.  Around one months. I still have a lot of experience in reading this book. Just write down the feeling of reading. Because people's memory is too weak, forget half a week, two weeks forget 70%. I'm afraid not to write it down.  Half a year later I basically don't remember what I said. This is basically a comparison with OC, and after three chapters of the three project author's development method of my current development mode of reflection. one, Swift compared to OC, the philosophy it expresses is: safe, concise。 These two points are everywhere in normal programming, for example:
classDog: NSObject {
     letorigin: String = "China"
     fileprivatevarname: String?
     privatevarage: Int?
    
     init (_name: String ?, age: Int = 1) {
         self.name = name ?? "Mong Choi"
         self.age = age
     }
}


Defines a dog class, a constant "origin", which can only be assigned once when a variable is defined as a let type. "Name" and "age" are two nullable types of variables. Overloaded with an Init method, there are two parameters in the Init method. "Name" is a nullable type, and the default value for "Age" is one. Assign these two variables to the property in the Init method. Where the name is determined to have a value set name, the default value "Wang Choi" is set to null.


Defining a class requires just a few lines of code, which is a lot simpler than OC. On the safe: display identifies which variables are nullable and which variables are not modifiable. That improves performance and improves security. Block code blocks in 2.OC are replaced by closures in SwiftIn Swift, the function is also a class citizen, as is the basic type. You can do properties, function arguments, and return values free of use. It is defined in a way that differs greatly from OC, such as: definition of swift and OC
   let sum: ((Int,Int) -> Int) = {(a, b) in
            returna + b
     }
     let res = sum(1, 2)
     print(res)

    int(^SumBlock) (int, int) = ^(intx, inty) {
        return  x + y;
    };
3. Differences in string usageFor the usual use of more string processing, the change is still relatively large.
let str = "hello world"
var str0 = str.prefix (2) // The first two
var str1 = str.suffix (2) /// The last two
        
let index0 = str.index (str.endIndex, offsetBy: -4)
var str2 = str [index0 .. <str.endIndex] // Next 4
        
let index1 = str.index (str.startIndex, offsetBy: 4)
var str3 = str [str.startIndex .. <index1] // First 4


Comparison with OC


NSString*str = @"hello world";
    id str0 = [str substringToIndex:2];
    id str1 = [str substringFromIndex:str.length-2];
    id str2 = [str substringWithRange:NSMakeRange(2, 3)];




4. In Swift, the use of structs is very extensive, and its role and usage are similar to that of classes, the main difference being that structs cannot be inherited. So consider that if the type is not inherited to generate subclasses, you can use struct-body substitution. In addition, the structure nesting is a large part of Swift and OC.
struct Animal {
     let region = "China"
     var name: String?
     var color = UIColor.red
     
     init (name: String, color: UIColor) {
         self.name = name
         self.color = color
     }
    
     struct Dog {
         let legNum = 4
         func run ()-> String {
             return "run home"
         }
     }
}




5. Enumeration. The enumeration provided by Swift is much more powerful than OC. Enumerations can continue to define enumerations, structs, classes, methods. Very flexible.
enum SDCEnumType: Int{
    case circle = 20
    case check
    
    func enumTypeString(type: SDCEnumType) -> String{
        switch type {
        case .circle:
            return"circle"
        default:
            if type.rawValue== 21{
                return"check"
            } else{
                return"其他情况"
            }
        }
    }
    
    enum SDCEnumSubType {
        case square(SDCEnumType)
        case ellipse(SDCEnumType)
    }
}
The protocol provided by 6.swift is also very flexible and can be extended by protocol, protocol inheritance, initialization method, protocol association and so on.
protocol Student {
    var name: String{getset}
    var age: Int{get}
    static func study(date:Date) -> Date
    
    init(name:String)
}
extension Student{
    var score:Float{
        return80.8
    }
    
}
protocol Childe:Student{
    
}




7. The following MAC,IPHONE,OC and Swift Hybrid Project gave me an understanding of the programming process:1. Usually very little attention to the development of Mac programs, this book in the following example wrote a Mac app demo. A certain understanding of MAC applications. 2. The programming step is divided into two steps: one, realizes the function. Second, the design mode adjustment. This two step in the normal programming, I just Do code implementation, for the completion of the function of the design pattern optimization is not done. Think of work for so long, programming is only half gone, really ashamed. 8. Use of the model. The common scenario in OC is the limitation of the content of the collection, and in Swift, the paradigm already involves functions. This instantly increases the effectiveness of the function by 10 times times. Swift is a strongly typed language, and the types on both sides of the same operator must be consistent.
func SwapTwoValues <T> (inout a: T, inout b: T) {
     let tempValue = a
     a = b
     b = tempValue
}
 
structIntStack {
     var items = [Int] ()
     // Push the stack
     mutating func push (item: Int) {
         items.append (item)
     }
     // pop out
     mutating func pop ()-> Int {
         return items.removeLast ()
     }
}
 
struct Stack <Ele> {
     var items = [Ele] ()
     mutating func push (item: Ele) {
         items.append (item)
     }
     mutating func pop ()-> Ele {
         return items.removeLast ()
     }
}
9. In Swift, each operator is actually a function. This has a conceptual difference from OC.
// Front operator, which represents the power of var0 of 2
prefix operator ^
prefix func ^ (var0: Double)-> Double {
     return pow (2, var0)
}
// Post operator, which means the second power of var0
postfix operator ^
postfix func ^ (var0: Double)-> Double {
     return var0 * var0
} 




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.