Abstract


When we learn something new, we usually do not start from zero, but start from what we know, compare the new thing with the known, so as to quickly understand the new thing in a comprehensive way. I am familiar with Java, so WHEN LEARNING Swift, I will compare Swift with Java and think about it. This paper is the conclusion of such thinking.

When we learn something new, we usually do not start from zero, but start from what we know, compare the new thing with the known, so as to quickly understand the new thing in a comprehensive way. I am familiar with Java, so WHEN LEARNING Swift, I will compare Swift with Java and think about it. (The sample code is from The Swift Programming Language)

An overview of

Getting from Java to Swift is relatively easy. Swift is much closer to Java syntax than Object-C, and more like Kotlin recently. Swift supports both object-oriented and functional programming. Swift is more powerful and user-friendly than Java. A rough comparison of Java and Swift is available online: [1]

[2]

Based on some

1.Swift doesn’t have a main function, which is a bit like a scripting language. Swift’s default entry is the main. Swift file. In iOS apps, the appdelegate. Swift file for @UIApplicationMain is usually marked. This is analogous to the Application defined in Androidmanifest.xml in Android. 2.Swift does not need to define a line terminator, which is like a scripting language. 3.Swift uses var to define variables. Generally, there is no need to specify the specific data type, and the compiler will judge by itself. In cases where the compiler cannot determine, you need to specify it explicitly yourself.

Int x = 0; //Swift defines the variable, and the compiler automatically recognizes the data type ver x = 0; Int ver y :long = 0; Swift y :long = 0; Swift y :long = 0;Copy the code

4.Swift uses let to define constants. Java is static final. 5. Array is the same concept as array in Java. A dictionary is a Map in Java. The value of dictionary is dictionary[key], and the interface is simple and convenient, just like array. 6. Nil in Swift is like null in Java. Nil means no initialization, no value. 7. Optional value means that the value can be nil. Swift defaults that a var cannot be assigned nil unless it declares optional. Optional cannot print directly, but must unwrap, as in optionalValue! . A bit like the NULL judgment packaged in Java. Can also use! Instead of? Declare a var that does not require unwrap.

Logic control

1.Swift’s switch syntax is similar to Java and C++, but it has no break. It will automatically exit the switch after hitting a case. If several different cases are processed in the same way, the case can be followed by several conditions separated by commas.

switch value {
case condition1:
    response to condition 1
case condition2, condition3:
    resoponse to condition 2 or 3
default:
    otherwise, do something else
}
Copy the code

2.Swift switch supports arithmetic, which means not just equal, but satisfying certain requirements.

 let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
    print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
    print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
    print("(\(x), \(y)) is just some arbitrary point")
}
// prints "(1, -1) is on the line x == -y"

Copy the code

3. The while loop is basically the same as in Java or C++, except that condition follows while without parentheses. 4. The for loop is basically the same as Java, but without parentheses. In the for loop,.. The use of < is convenient. It also supports the _ wildcard, similar to the For each loop in Java.

1. Functions are defined quite differently from Java. Swift functions are defined as func functionName(argName: Type) -> Return Type:

 func sayHelloAgain(personName: String) -> String {
    return "Hello again, " + personName + "!"
}
Copy the code

2. The Swift function can return multiple return values, which is really powerful.

func minMax(array: [Int]) -> (min: Int, max: Int) {
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1.. currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}
Copy the code

3.Swift function can receive indefinite parameters, basically similar to Java usage. 4. Functions can be nested, this is Java or C++ do not have, very good use. For example, there is often a piece of logic that is too long to be implemented by a single function. In Java or C++, it is common to break it up into several functions, keeping each function short and single. But such split functions are not a good indication that they are functional and not cohesive enough. This nested Swift function can be better implemented.

func chooseStepFunction(backwards: Bool) -> (Int) -> Int {

    func stepForward(input: Int) -> Int { 
        return input + 1 
    }

    func stepBackward(input: Int) -> Int { 
        return input - 1 
    }

    return backwards ? stepBackward : stepForward
}


Copy the code

5.Swift supports function types. A function type is determined based on input parameters and return values. Function types allow functions to be used just like normal data types. For example, the argument to a function can be another function, not the return value of another function, but another function, as long as the type matches. This is quite a function-level polymorphism, which is really a bit aggressive.

// define a function of type (Int, Int)->Int func addTwoInts(a: Int, _ b: Int) -> Int {return a + b} // define another function where one argument is (Int, Int) -> Int function func printMathResult(mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { print("Result: \(mathFunction(a, b))")} printMathResult(addTwoInts, 3, 5)Copy the code

6.Swift supports closure, which I think can be understood as “anonymous function”. It only needs to describe input and output, and use IN to separate input and output description.

Class and structure

1. The constructor of the class, called init(). Class function calls are basically the same as Java and C++. Self is equivalent to this in Java. 2. The member access permission control levels of class in Swift are public, internal, and private, which correspond to public, protected, and private in Java. 3. Deinit is destructor. Java also has a finalize() function. However, Java’s Finalize () function is not guaranteed to be called, so override is not recommended. 4. Class inheritance is a bit like C++, using:.

class SomeSubclass: SomeSuperclass {
    // subclass definition goes here
}
Copy the code

5. Unlike Java, its setters and getters are called implicitly. I think Swift is designed in such a way that the user cares only about the inputs and outputs and nothing else. For example, you only need to care about the need for set or get. The specific set and GET functions are encapsulated and do not concern the user. For example, the type of method mentioned above, as long as the input and output are defined, a class of method is defined, then there can be multiple specific implementations of this type.

Struct Point {var x = 0.0, y = 0.0} struct Size {var width = 0.0, Height = 0.0} struct Rect {var origin = Point() var size = size () var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set(newCenter) { origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } } } Var square = Rect(origin: Point(x: 0.0, y: 0.0), size: size (width: 10.0, height: 0) Square. Center = Point(x: 15.0, y: 15.0)) let initialSquareCenter = square.center square.center = Point(x: 15.0, y: 0) 16.0) print("square.origin is now at (\(square.origin), \(square.origin))")Copy the code

6.Swift enumeration is similar to Java in that it is essentially a class that can contain functions. 7. Struct is written in the same way as class. The difference is that struct passes a copy of the content, while class passes a reference. This is awesome. 8. Enumerations also support associated values, which Java does not.

enum Barcode {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)
}

var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
Copy the code

9. Protocol is similar to Java interface. 10. Extension is powerful and even abnormal. It can dynamically add functions and member variables to a class and dynamically make a class implement a protocol without modifying the source code of the class. New member variables, new functions, implementing an interface, Java can only do that through inheritance. This is implemented directly and applies to all objects of that class, including those created earlier.

Extension Double {var km: Double {return self * 1_000.0} var m: Double {return self} var cm: Double {return self / 100.0} var mm: Double {return self / 1_000.0} var ft: Double {return self / 3.28084}} let oneInch = 25.4.mm print("One inch is \(oneInch) meters") // prints "One inch is Meters "let threeFeet = 3. Ft print("Three feet is \(threeFeet) meters") // prints "Three feet is 0.914399970739201 meters"Copy the code

Similar to Java, Swift generics support where statements, which allow for more fine-grained control over types.

func allItemsMatch< C1: Container, C2: Container where C1.ItemType == C2.ItemType, C1.ItemType: Equatable> someContainer: C1, _ anotherContainer: C2 -> Bool { // check that both containers contain the same number of items someContainer.count ! = anotherContainer.count { return false } // check each pair of items to seethey are equivalent for i in 0.. <someContainer.count { someContaineri] ! = anotherContaineri] { return false } } // all items match, so return true return true }Copy the code

Memory management

Similar to Java, Swift does not need to manage its own memory. Swift uses the Automatic Reference Counting (ARC) mechanism to reclaim memory, while Java uses the garbage collection mechanism to ensure that memory can be reclaimed in a timely manner. But the recycling mechanism is different. My understanding is that Swift’s ARC mechanism focuses on invalid objects, objects that are not referenced by anyone. Therefore, if two objects are referenced in a loop, they cannot be recycled, causing leaks. Weak Reference or Unowned Reference is needed to break the loop. Java’s garbage collection mechanism, on the other hand, focuses on what are valid objects, i.e. objects referenced by GC Root are valid and the rest are invalid. So even objects that reference each other that are not referenced by GC Root will be collected by the garbage collector. From this point of view, Java’s strategy is superior. This shows how important it is to look at things from a different Angle.

Refer to the reference

  1. The Swift Programming Language (Swift) 2.1 developer.apple.com/library/ios…
  2. what is the entry point of swift code execution? Stackoverflow.com/questions/2…
  3. Swift program entry in-depth analysis 00red.com/blog/2014/1…
  4. Codebuild. me/2015/09/15/…
  5. Java vs Swift slidenerd.com/2014/11/15/…
  6. SwiftGuide github.com/ipader/Swif…
  7. Swift developer.apple.com/swift/
  8. Learn the Essentials of Swift developer.apple.com/library/pre…
  9. What is an “unwrapped value” in Swift? Stackoverflow.com/questions/2…
  10. Automatic reference count numbbbbb.gitbooks. IO /-the-swift-…