Swift GYB

The term "model" can be traced back to the early stages of the print media. The filling amount of smaller regional newspapers only a few inches, but often lack the writing staff to achieve this goal, so many of them are turning to large print groups in order to obtain a steady stream of content, you can literally add to their daily post page . These stories are usually provided in the pre-board, which is similar to rolled steel used in the manufacture of boilers, hence the name.

Through a process of metonymy, the content itself is known as a "model", and the concept was used to standardize the text contained a formula in the contract, the most relevant form of letters, as well as the code on NSHipster this week's article.

Xiao Bian to have technical exchange group to chat no technology to learn 691 040 931

Not all code is charming. In fact, many of the low-level work so that all infrastructure is a template.

This is a standard library Swift, including as signed integer type Family (true Int8, , Int16, Int32), Int64which vary only in the size of the corresponding type of implementation.

Copy and paste the code can be used as a one-time solution (assuming that the first time you try to correct), but it is not sustainable. Whenever you want to make changes to achieve those derived, you may introduce minor inconsistencies, leading over time to achieve and disagreements - and random mutation responsible for changes in the Earth life different.

There are a variety of language techniques to deal with this problem, and from C ++ templates to Lisp macros evalpreprocessor statement C.

Swift is no macro system, and because the standard library itself is written in Swift, so it can not use C ++ meta-programming features. Instead, Swift defenders use a program called gyb.py Python scripts, using a  group  template label generation source code.

GYB  is "Generate Your Boilerplate" acronym, another Python reference tool,  GYP  ( "build your project")   Haskell包 SYB (“Scrap Your Boilerplate”) 

How GYB operation

GYB is a lightweight template system that allows you to use the Python code and replace variable flow control:

  • Python code sequence evaluation section%{ <var class="placeholder" style="box-sizing: border-box; background: rgb(248, 248, 242); display: inline-block; padding: 0px 0.25em; border: 1px solid rgb(40, 42, 54); border-radius: 5px; font-style: normal;">code</var> }
  • Sequence control flow management% <var class="placeholder" style="box-sizing: border-box; background: rgb(248, 248, 242); display: inline-block; padding: 0px 0.25em; border: 1px solid rgb(40, 42, 54); border-radius: 5px; font-style: normal;">code</var>: ... % end
  • Alternatively the result of the expression sequence${ <var class="placeholder" style="box-sizing: border-box; background: rgb(248, 248, 242); display: inline-block; padding: 0px 0.25em; border: 1px solid rgb(40, 42, 54); border-radius: 5px; font-style: normal;">code</var> }

All other text is unchanged.

Can Codable.swift.gyb the find GYB is a good example. At the top of the file, group Codabletype is assigned to instance variables:

%{
codable_types = ['Bool', 'String', 'Double', 'Float',
                 'Int', 'Int8', 'Int16', 'Int32', 'Int64',
                 'UInt', 'UInt8', 'UInt16', 'UInt32', 'UInt64']
}%

复制代码

Later, in implementation, iterative methods to generate these types of agreements required statement:Single<wbr style="box-sizing: border-box;">Value<wbr style="box-sizing: border-box;">Encoding<wbr style="box-sizing: border-box;">Container

% for type in codable_types:
  mutating func encode(_ value: ${type}) throws
% end

复制代码

GYB assessment template produces the following statement:

mutating func encode(_ value: Bool) throws
mutating func encode(_ value: String) throws
mutating func encode(_ value: Double) throws
mutating func encode(_ value: Float) throws
mutating func encode(_ value: Int) throws
mutating func encode(_ value: Int8) throws
mutating func encode(_ value: Int16) throws
mutating func encode(_ value: Int32) throws
mutating func encode(_ value: Int64) throws
mutating func encode(_ value: UInt) throws
mutating func encode(_ value: UInt8) throws
mutating func encode(_ value: UInt16) throws
mutating func encode(_ value: UInt32) throws
mutating func encode(_ value: UInt64) throws

复制代码

This pattern is used throughout this document, a method to produce a similar statement similarly formulated, and. Overall, GYB will reduce the amount of boilerplate code of thousands of LOC:encode(_:for<wbr style="box-sizing: border-box;">Key:)``decode(_:for<wbr style="box-sizing: border-box;">Key:)``decode<wbr style="box-sizing: border-box;">If<wbr style="box-sizing: border-box;">Present(_:for<wbr style="box-sizing: border-box;">Key:)

$ wc -l Codable.swift.gyb
2183 Codable.swift.gyb
$ wc -l Codable.swift
5790 Codable.swift

复制代码

Effective GYB templates may not generate valid Swift code. If the compiler error derived files, it may be difficult to determine the root cause.

Installation GYB

GYB is not a standard part of the Xcode tool chain, so you can not find it xcrun. Instead, you can use the Homebrew download it:

$ brew install nshipster/formulae/gyb

复制代码

Alternatively, you can download the source code and use chmodcommand to generate gyban executable file (installed by default on macOS should be able to run gyb):

$ wget https://github.com/apple/swift/raw/master/utils/gyb
$ wget https://github.com/apple/swift/raw/master/utils/gyb.py
$ chmod +x gyb

复制代码

If you go this route, be sure to move them to a place that can be accessed from Xcode project, but they want to separate from the source file (for example, Vendordirectory under the project root directory).

Use GYB in Xcode

In Xcode, click the blue icon in the project file navigator, select the activity in the target project, and then navigate to the "Build Phases" panel. At the top, you will see a +sign, you can click on the symbol to add a new building phase. Select "Add new run the script stage", and then enter the following in the Source Editor:

find . -name '*.gyb' |                                               \
    while read file; do                                              \
        ./path/to/gyb --line-directive '' -o "${file%.gyb}" "$file"; \
    done

复制代码

GYB order to ensure that the construction phase before compiling the source.

Now, when you build the project, have any .swift.gybfile extension by GYB assessment, GYB will output a .swiftproject with the rest of the code is compiled files.

When to use GYB

As with any tool, how to know when to use it is as important to understand. Here are some examples you can open the Toolbox and enter GYB.

Code generation formula

Are you paste the same code to copy the items in a set of elements or sequence? With variable substitution for-in loop may be the solution.

As Codablefrom the previous example shown, you can set a declared at the top GYB template file, then loop type for the collection, property or method declaration:

%{
    abilities = ['strength', 'dexterity', 'constitution',
                 'intelligence', 'wisdom', 'charisma']
}%
class Character {
  var name: String

% for ability in abilities:
  var ${ability}: Int
% end
}

复制代码

GYB evaluated using the following Swift Code is generated:

class Character {
  var name: String

  var strength: Int
  var dexterity: Int
  var constitution: Int
  var intelligence: Int
  var wisdom: Int
  var charisma: Int
}

复制代码

A lot of code duplication is an odor may indicate that a better way to accomplish the task. And generic protocol extensions such as built-in language function can eliminate a lot of code duplication, so be careful to use them instead of using GYB enforcement.

Code generated from the data derived

You are writing code in the data source based on it? Try GYB part of your development!

GYB files can be imported as Python package json, xmland csvso you can analyze files may be encountered almost any type:

%{ import csv }
% with open('path/to/file.csv') as file:
    % for row in csv.DictReader(file):

复制代码

If you want to see this, please see  Currencies.swift.gyb  , it is ISO 4217 each defined specifications monetary generation Swift enumeration.

By downloading the data to be checked into source control files rather than HTTP request or query the database in GYB file, the compiler can maintain the fast and deterministic.

Code generation makes your code to keep pace with the standards become negligible. Just update the data file and re-run GYB can.


Swift has done a lot with another compiler synthesis of recently cut model  Encodableand Decodable4.0,  Equatableand Hashable4.1, and 4.2. We hope that this momentum will be reflected in future language updates.Case<wbr style="box-sizing: border-box;">Iterable

At the same time, for everything else, GYB is a useful tool for code generation.

Another great tool is the community  Sourcery , which allows you to Swift (through Stencil authoring templates) instead of Python.

"Do not repeat yourself" may be programming a virtue, but sometimes you have said several times in order to make things work. When you do this, you will be grateful for a tool like GYB to say to you.

Scan code into the exchange group chat did not have technology to technology to learn

Address reprint Original: nshipster.com/swift-gyb/

Reproduced in: https: //juejin.im/post/5d079e50f265da1b667bdc07

Guess you like

Origin blog.csdn.net/weixin_33812433/article/details/93182118