Swift basic syntax


Release date:2023-11-23 Update date:2023-12-11 Editor:admin View counts:305

Label:

Swift basic syntax

In the previous chapter, we talked about how to create “Hello, World!” in the Swift language. program. Now let’s review.

If you are creating an OS X playground, you need to introduce Cocoa:

import Cocoa

/* My first Swift program */
var myString = "Hello, World!"

print(myString)

If we want to create iOS playground, we need to introduce UIKit:

import UIKit
var myString = "Hello, World!"
print(myString)

Execute the above program, and the output is as follows:

Hello, World!

The above code is the basic structure of the Swift program, and then we willexplain the components of the structure in detail.

Swift introduction

We can use it. import statement to introduce any Objective-C framework (or C library) into the Swift program. For example import cocoa statement is imported using the Cocoa library and API, which we can use in Swift programs.

Cocoa itself is written by Objective-C language, and Objective-C is a strictsuperset of C language, so in Swift applications we can easily mix C language code, even C++ code.

Swift marker

The Swift program consists of a variety of tags, which can be words, identifiers, constants, strings or symbols. For example, the following Swiftprogram consists of three tags:

print("test!")

The above statement consists of three symbols: word ( print ), symbol (( ), string ( "test" ).

print
(
   "test!"
)

Annotation

Swift comments are very similar to the C language, with single-line commentsbeginning with two backslashes:

//This is a line of comments

Multiline comments to / start with / end:

/* This is also a comment,But spanning multiple lines */

Unlike multiline comments in the C language, multiline comments for Swift can be nested within other multiline comments. It is written by inserting another multiline comment within a multiline comment block. When the second comment block is closed, it is still followed by the first comment block:

/*This is the beginning of the first multiline comment
/*This is the second nested multiline comment*/
This is the end of the first multi line comment*/

The nesting of multi-line comments allows you to comment blocks of code morequickly and easily, even if there are already comments in the block.

semicolon

Unlike other languages, Swift does not require a semicolon (;) at the end ofeach line of statements, but when you write multiple statements in the sameline, you must separate them with a semicolon:

import Cocoa
/* My first Swift program */
var myString = "Hello, World!"; print(myString)

Identifier

Identifiers are names assigned to variables, constants, methods, functions, enumerations, structures, classes, protocols, and so on. There are certain norms for the letters that make up identifiers, and the naming rules for identifiers in Swift are as follows:

  • Case sensitive, Myname and myname are two different identifiers

  • The first character of an identifier can start with an underline (_) or a letter, but cannot be a number;

  • Other characters in the identifier can be underscores (_), letters, or numbers.

For example: userNameUser_Name_sys_val , height, etc. are legal identifiers, while 2mailroom# and class is an illegal identifier.

Note: the letters in Swift are encoded by Unicode [1] . Unicode is called unified coding system, which contains Asian characters such as Chinese, Japanese, Korean and even emoticons that we use in chat tools.

If you must use a keyword as an identifier, you can add an accent (`) beforeand after the keyword, for example:

let `class` = "Runoob"

Keyword

Keywords are reserved character sequences similar to identifiers and cannot be used as identifiers unless they are enclosed in an accent (`). Keywords are predefined reserved identifiers that have a special meaning to the compiler. There are four common keywords.

Keywords related to the declaration

Class

Deinit

Enum

Extension

Func

Import

Init

Internal

Let

Operator

Private

Protocol

Public

static

Struct

Subscript

Typealias

Var

Keywords related to statements

Break

Case

Continue

Default

Do

Else

Fallthrough

For

if

In

Return

Switch

Where

While

Expression and type keywords

As

DynamicType

False

Is

Nil

Self

Self

Super

True

_COLUMN_

_FILE_

_FUNCTION_

_LINE_

Keywords used in a particular context

associativity

Convenience

Dynamic

DidSet

Final

Get

Infix

inout

Lazy

Left

Mutating

None

Nonmutating

Optional

override

postfix

Precedence

Prefix

Protocol

Required

Right

set

Type

Unowned

Weak

WillSet

Swift Spac

Swift language does not completely ignore spaces like C/C++ or Java. Swift has certain requirements for the use of spaces, but it is not as strict as Python’s requirements for indentation.

In Swift, operators cannot follow variables or constants directly. For example, the following code reports an error:

let a= 1 + 2

The error message is:

error: prefix/postfix '=' is reserved

It probably means that the equal sign comes directly before or after it. This usage is reserved.

The following code still reports an error (continue to pay attention to the spaces):

let a = 1+ 2

The error message is:

error: consecutive statements on a line must be separated by ';'

This is because Swift thinks that the statement is over by 1 +, and 2 is thenext statement.

Only by writing in this way will you not make a mistake:

let a = 1 + 2;  // This writing method is recommended for coding specifications
let b = 3+4 // This is also okay

Swift literal quantity

A literal quantity is a value such as a specific number, string, or Boolean value that can directly indicate its own type and assign a value to a variable. For example, in the following:

42//integer literal
3.14159//Floating-point literal
Hello, world! "//String literal
True//Boolean literal

Printout

Swift usage print function printout:

print("Runoob") // output Runoob

print the function is a global function, and the complete function signature is:

public func print(items: Any..., separator: String = default, terminator: String = default)

If we want it not to wrap, we just need to assign the last parameter to an empty string:

for x in 0...10{
    print("\(x) ", terminator: "")
}
print()

The output is as follows:

0 1 2 3 4 5 6 7 8 9 10

If you need to receive user input, you can use the readLine() :

let theInput = readLine()

Powered by TorCMS (https://github.com/bukun/TorCMS).