How do I convert JavaScript to Swift? (a)

How do I convert JavaScript to Swift? (2)

The effect that has been achieved so far

Yesterday I asked a colleague to write some random JavaSCript code:

function showdata() {
  var array = [0.1.2.3.4];
  var result = true;

  if (result) {
    for (let index = 0; index < array.length; index++) {
      console.log(array[index]); }}else {
    console.log("noooooo!")}var obj = {
    name: 'wuli'.sex: 0.age: 21
  };
  var string = "woxinshensihai";
  if (result) {
    console.log(string)
  }
  console.log(obj);
}
Copy the code

Then use the translation program to translate, the results are as follows:

func showdata(a) {
    var array = [
        0.1.2.3.4,]var result: Bool = true
    if result {
        for (index, item) in array.enumerated() {
            print(array[index])
        }
    } else {
        print("noooooo!")}var obj = NamesexageModel(name: "wuli", sex: 0, age: 21)
    var string: String = "woxinshensihai"
    if result {
        print(string)
    }
    print(obj)
}

Copy the code

Generated Model file:

class NamesexageModel: NSObject { 
  var name: String
  var sex: Int
  var age: Int
}
Copy the code

From the looks of it, it feels ok…

For loop translation

The translation of the for loop was not covered in the previous article, so here’s a sidebar:

JavaScript’s For notation is quite different from Swift’s, mainly because arrays in JavaScript are not like arrays in most other languages. First, arrays in Javascript are not contiguously in memory, and second, an Array’s index is not an offset. In fact, the Array index is not a Number, but a String index. The reason we can write it correctly like array[0] is that the language automatically converts a 0 of Number to a 0 of String

C-style for loops

This is probably the most common script in JavaScript

for (let index = 0; index < array.length; index++) {
    console.log(array[index]);
}
Copy the code

But Swift doesn’t support c-type writing since Swift3.0, which is a bit of a pain

For loop in Swift

for (index, item) in array.enumerated() {
    print(array[index])
}
Copy the code

Let index = 0; let index = 0; let index = 0; index < array.length; Index++ code

Let’s look at the AST for the for loop:

"body": [{"type": "ForStatement"."init": {
        "type": "VariableDeclaration"."declarations": [{"type": "VariableDeclarator"."id": {
              "type": "Identifier"."name": "index"
            },
            "init": {
              "type": "Literal"."value": 0."raw": "0"}}]."kind": "let"
      },
      "test": {
        "type": "BinaryExpression"."left": {
          "type": "Identifier"."name": "index"
        },
        "operator": "<"."right": {
          "type": "MemberExpression"."object": {
            "type": "Identifier"."name": "array"
          },
          "property": {
            "type": "Identifier"."name": "length"
          },
          "computed": false}},"update": {
        "type": "UpdateExpression"."operator": "+ +"."prefix": false."argument": {
          "type": "Identifier"."name": "index"}}... .Copy the code

For (let index = 0; for (let index = 0; index < array.length; Index ++) {convert to for (index, item) in array.enumerated()

ifResult.push (stmt.test.left. Name) result.push(stmt.test.left. Name) result.push(stmt.test.left.', item) in ') / / keyword result obtain array. Push (STMT. Test. Right. The object. The name) result. Push ('.enumerated()')}Copy the code

For (index, item) in array.enumerated()

This code is used to generate index ++) just comment it out or delete it

if (stmt.update) {
    result.push(space);
    result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT));
    result.push(') ');
} else {
    result.push(') ');
}
Copy the code

ForIn the for loop

for (index in array) {
 console.log(array[index]);
}
Copy the code

ForOf the for loop

for (let item of array) {
  console.log(item);
}
Copy the code

The equivalent in Swift:

for item in array {
    print(item)
}
Copy the code

It’s a little bit easier to translate just by changing “of” to “in.

Code formatting

The code generated by the translator is not very beautiful in terms of format. Here we use SwiftFormat to format the code. Swiftformat is very simple to install, just need:

> brew update
> brew install swiftformat
Copy the code

Swiftformat Filename. swift — swiftVersion 4.2

const { exec } = require('child_process');
exec('swiftformat ./Swift_Code/' + fileName + 'swift -- swiftversion 4.2', (err, stdout, stderr) => {
    if(err) {
        return; }})Copy the code

As for how to translate JavaScript’s network request, JavaScript and Swift have their own network request libraries, so they need to unify method names and parameters, and each language also needs to encapsulate their own network request libraries. Second, Swift JSON parsing requires a ClassModel, where you need to transfer JSON to Swift Model Class……

To be continued…