Swift Foundation Learning (i) basic grammar

Source: Internet
Author: User
Tags naming convention

  Introduction to Swift (a compliment, a collection of a number of language profiles on Swift learning Tutorials have always thought that English and Chinese are mixed with the English letter at the end of the place to play a space, the original is the beginning and end of the English alphabet to add a space, The English alphabet is followed by punctuation without spaces ):

Swift is a new programming language for writing Ios,macos,watchos and TvOS applications. Swift combines the advantages of C and objective-c and is not limited by C compatibility. Swift uses a secure programming model and adds a lot of new features, which makes programming easier, more flexible, and more fun. Swift is based on a mature and beloved Cocoa and Cocoa Touch framework, and its advent will redefine software development.

Swift's development began a long time ago. To lay the groundwork for Swift, Apple has improved the compiler, debugger, and framework structure. We use automatic reference counting (Automatic Reference counting, ARC) to simplify memory management. We build a framework stack based on foundation and Cocoa to modernize and standardize it completely. The objective-c itself supports blocks, set syntax, and modules, so the framework can easily support modern programming language technology. Thanks to these basic work, we can now publish such a new language for future development of Apple software.

Objective-c developers are not unfamiliar with Swift. It uses objective-c named parameters and the dynamic object model to seamlessly connect to the existing Cocoa framework and can be compatible with OBJECTIVE-C code. On top of this, Swift has many new features and supports procedural and object-oriented programming.

Swift is also very friendly for beginners. It is the first system programming language that satisfies both industry standards and is as expressive and interesting as the scripting language. It supports code previews (playgrounds), a revolutionary feature that allows programmers to run Swift code without compiling and running the application and view the results in real time. Playground will do the compiling for us in real time as we write code, and automatically show us the execution results of each line of code, whether it's a simple statement, a loop, or even a variety of ui,playground, which is a great tool to understand the various language features in Swift. The coding of our learning process is basically carried out under the playgrounds, greatly improving the efficiency of our study, what we have written is seen.

Swift combines the essence of modern programming language with the wisdom of Apple's engineer culture. The compiler optimizes performance and the programming language optimizes development, with both the fish and the paws. Swift can be used to develop small programs such as "Hello, world" or to develop a complete set of operating systems. All of these features make Swift a worthwhile investment for both developers and Apple.

Swift is a great way to write Ios,macos,watchos and TvOS applications and will evolve with new features and functionality.

Swift provides all the underlying data types for C and objective-c, including integer Int, floating-point number Double, float, boolean bool, and string string (string type is no longer a character array, in Swift string Not a collection type, the string is optimized in Swift). Swift also provides two powerful sets of data types, including array (array) and dictionary (dictionary). In addition to the familiar types, Swift introduces advanced types that cannot be implemented in OBJECTIVE-C. These include tuples, which enable you to create and pass value groupings. Tuples can return multiple values from a function as a single compound value.

Like C, Swift uses variables to store and access numeric values. Swift also supports variables that cannot be changed, which we call constants in C, but constants in Swift will be more powerful. Constants can be used when the value of the variable does not need to be changed, which makes the code more secure and concise.

In addition, Swift introduces some advanced data types that are not available in objective-c, such as tuples (tuples), which allows you to create and pass a set of values.

Swift also introduces the option type (optionals), which is used to handle cases where the value of the variable does not exist. There are two possible options: one is the existence of a variable, such as equals X, and two is a variable value that does not exist at all. Optionals is similar to the pointer to nil in Objective-c, but applies to all data types, not just classes, optionals is more secure and concise than the nil pointer in Objective-c, and is the core of Swift's most powerful features. Heart.

Swift is a type of safe language, Optionals is representative. Swift can help you work in a type-safe environment, and if you need to use String types in your code, Swift's security can prevent you from mistakenly passing Int values, which allows you to detect and fix problems in a timely manner during the development phase.

  Hello, world!.

Print "Hello, world!" on the screen, which can be implemented in a line of code in Swift:

1  Print ("Hello, world! ")
1 NSLog ("Hello, world! ")

Write the C and OC code print "Hello, world!", should be particularly familiar with this form, in Swift, this line of code is a complete program. There is no need to import a separate library for input or output or string processing, and the code in the global scope is automatically used as the entry point for the program, so there is no need for a main()  function.

  Swift: Use of semicolons

A semicolon is no longer required at the end of each line of independent code in Swift, and is separated by semicolons if multiple statements are written in the same line.

1 // The first statement is to define a variable, STR, and assign the initial value "Hello, playground", followed by four print statements, separated by semicolons (at this point after the last NSLog with semicolons do not add semicolons) 2 var " Hello, playground. "; Print (str); Print (str); NSLog (str); NSLog ("xxx\ (str)")

  Swift: Introducing

Use the import statement to introduce any OBJECTIVE-C framework (or C library) into the Swift program. For example, import cocoa statements are imported using the Cocoa libraries and APIs, and we can use them in Swift programs.

Cocoa itself is written by objective-c language, Objective-c is a strict superset of C language, so in Swift application we can easily mix C language code, even C + + code.

1 // introduction of the Uikit framework 2 // Introducing the Foundation framework 3 //

  Swift: Notes

Two backslashes start with a single-line comment, and OC and Swift remain the same:

1 // This is a single-line comment

Three backslashes are one of the markup notation notation, and OC and Swift remain the same:

 1  ///  Tag Annotations  
1     /// Test Tag Comments 2     /// 3     /// -Parameter Person: number of persons 4     /// -Returns:hml 5     Func test (Person:int), String {6        print (person)7          return"HML"8     }

Tag annotations are used as follows:

Another way of marking annotations is to start with/** with the end of */, the contents of the middle wrap tag annotation, mark the comment more to mark the function's purpose, and the meaning of the attribute.

1 /* * 2 mark the contents of a comment 3  */

Multiline comments begin with/* and end with */and the contents of the comment in the middle:

1 /* 2 This is a multi-line comment 3  */

Unlike OC, Swift can nest multiple lines of comments inside multiple lines of comments, and OC is a direct error. The notation is to insert another multiline comment within a multiline comment block, while the second comment block is closed, followed by the first comment block.

1         /* 2          First Multiline comment start 3/         *4          Second multiline comment inside nested 5          */ 6          Second multi-line comment End 7          * /

  Swift: Identifiers

Like other languages, identifiers are names that are named for variables, constants, methods, functions, enumerations, structs, classes, protocols, closures, etc., and the strings that make up identifiers have certain rules, and the rules in Swift are as follows:

1. Letters are case-sensitive, such as "str" and "str" are two different identifiers.

2. The first character of an identifier can be a letter or an underscore, and can only begin with a letter or an underscore.

3. Identifiers can only be composed of letters, numbers, underscores, cannot contain symbols, such as "[Email protected]#$%^&* () ..." can never appear.

Note: The characters in Swift are Unicode encoded, Unicode is called unified encoding, it contains Asian text encoding, such as Chinese, Japanese, Korean and other characters, but also contains emoji expressions, so variables we can even use Chinese characters and emoji expression to name. If you must use a keyword as an identifier, you can add an accent mark (') around the keyword.

1 var " HML " 2 print ("\ (kanji)")34var" Family " 5 print ("\ (???????????) ")

  Swift: Keywords

A keyword is a system-reserved sequence of characters similar to an identifier naming convention, that is, a keyword is a predefined reservation identifier that has a special meaning to the compiler.

For example:

Keywords related to declarations: class, Func, let, public, Typealias, Deinit, import, operator, Static, Var, enum, init, private, struct, extension , internal, protocol, subscript

Keywords related to statements: Break, do, if, where, case, else, in, while, continue, Fallthrough, return, default, for, switch

Expressions and Type keywords: as, nil, true, _line_, DynamicType, Self, _column_, false, self, _file_, is, Super, _function_

Keywords used in a specific context: associativity, final, lazy, nonmutating, precedence, right, weak, convenience, get, left, optional, prefix, Set, Willset, dynamic, infix, mutating, override, Protocol, Type, Didset, InOut, none, Postfix, required, unowned

  Swift: Space

Swift has certain requirements for the use of spaces.

1. The operator cannot be directly behind a variable or constant.

A and = when connected together:

1 when connecting with +:

Tip Let's insert a delimiter after the plus sign, because Swift thinks the 1+ statement ends, and 2 is the next statement, so a separator symbol is inserted in the middle.

1 1 2//This is the standard recommended use of the wording 2 3+4//This is also possible


  Swift: Literal

Literal refers to a particular number, string, or Boolean value that, in this way, can directly indicate its own type and assign a value to the variable.

1  the // shaping literal 2 3.1415926 // floating-point literals 3 " Hello, worle!. " // string literal 4 true // boolean literal

Well, the basic grammar first write so much, the back of the time to use the details of a step-by-step study.

Reference Link: https://www.boxueio.com/category/swift








Swift Foundation Learning (i) basic grammar

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.