swift3到swift5_不到十分钟即可了解Swift的基础知识

swift3到swift5

by Saul Costa

由Saul Costa

Swift is a relatively new programming language designed by Apple Inc which was initially made available to Apple developers in 2014.

Swift是Apple Inc.设计的一种相对较新的编程语言,于2014年首次提供给Apple开发人员。

It was primarily intended as a replacement for the aging Objective-C language that was the foundation of OS X and iOS software development at the time. It was made open source in December 2015.

它主要是为了替代老化的Objective-C语言,后者是当时OS X和iOS软件开发的基础。 它于2015年12月开源。

While it remains primarily used by developers targeting the Apple macOS and iOS platforms, Swift is also fully supported on Linux, and there are unofficial ports under development for Windows as well.

尽管仍主要由面向Apple macOS和iOS平台的开发人员使用,但Linux上也完全支持Swift,并且Windows也在开发非官方端口。

Unlike many object-oriented languages, which are based on older procedural languages — for example, C++ and Objective-C are based on C — Swift was designed from the ground up as a new, modern, object-oriented language that makes programming faster and easier, and helps developers produce expressive code that’s less prone to errors than many languages.

与许多基于旧程序语言的面向对象语言(例如C ++和Objective-C基于C)不同,Swift是从头开始设计的,它是一种新的,现代的,面向对象的语言,可以使编程更快,更简单。更容易,并帮助开发人员生成具有表现力的代码,这种代码比许多语言更不容易出错。

While not based on an older language, Swift, in the words of its chief architect, Chris Lattner, “was inspired by drawing ideas from Ruby, Python, C#, CLU, and far too many others to list”.

虽然不是基于较旧的语言,但用其首席架构师Chris Lattner的话来说,Swift的灵感来自Ruby,Python,C#,CLU和太多其他的想法,以至于无法列出

In this quick crash course, we will cover the fundamentals of using the Swift programming language. You’ll learn:

在本快速速成课程中,我们将介绍使用Swift编程语言的基础知识。 您将学到:

  • Basic Swift syntax

    Swift基本语法
  • Swift program structure

    Swift程序结构
  • Variables and constants

    变量和常量
  • Type inference

    类型推断
  • Variable and constant naming conventions

    可变和常量命名约定
  • Printing and string interpolation

    打印和字符串内插

Let’s get started!

让我们开始吧!

This crash course is adapted from Next Tech’s full Beginning Swift course, which includes an in-browser sandboxed environment with Swift pre-installed. It also has numerous activities for you to complete. You can check it out for free here!

此速成班课程改编自Next Tech的完整Beginning Swift课程,其中包括一个预安装Swift的浏览器内沙盒环境。 它还有许多活动供您完成。 您可以在这里免费签出!

迅捷语法 (Swift Syntax)

In this first section, we’ll look at the basic language syntax for Swift.

在第一部分中,我们将介绍Swift的基本语言语法。

Like many modern programming languages, Swift draws its most basic syntax from the programming language C. If you have previous programming experience in other C-inspired languages, many aspects of Swift will seem familiar, for example:

与许多现代编程语言一样,Swift从编程语言C汲取最基本的语法。如果您以前有过其他以C语言为灵感的语言的编程经验,Swift的许多方面似乎都很熟悉,例如:

  • Programs are made up of statements, executed sequentially.

    程序由按顺序执行的语句组成。
  • More than one statement is allowed per editor line when separated by a semicolon (;).

    当用分号( ; )分隔时,每个编辑器行允许多个语句。

  • Units of work in Swift are modularized using functions and organized into types.

    Swift中的工作单元使用功能进行模块化并按类型进行组织。
  • Functions accept one or more parameters, and return values.

    函数接受一个或多个参数,并返回值。
  • Single and multiline comments follow the same syntax as in C++ and Java.

    单行和多行注释遵循与C ++和Java相同的语法。
  • Swift data type names and usage are similar to that in Java, C#, and C++.

    Swift数据类型的名称和用法与Java,C#和C ++中的相似。
  • Swift has the concept of named variables, which are mutable, and named constants, which are immutable.

    Swift具有可变的命名变量和不变的命名常量的概念。
  • Swift has both struct and class semantics, as do C++ and C#.

    Swift和C ++和C#都具有结构和类语义。

However, Swift has some improvements and differences from C-inspired languages that you may have to become accustomed to, such as:

但是,Swift与您可能必须习惯的以C语言启发的语言相比有一些改进和区别,例如:

  • Semicolons are not required at the end of statements — except when used to separate multiple statements typed on the same line in a source file.

    语句末尾不需要分号,除非用于分隔源文件中同一行上键入的多个语句。

  • Swift has no main() method to serve as the program’s starting point when the operating system loads the application. Swift programs begin at the first line of code of the program’s source file — as is the case in most interpreted languages.

    当操作系统加载应用程序时,Swift没有main()方法作为程序的起点。 Swift程序从程序源文件的第一行代码开始-就像大多数解释语言一样。

  • Functions in Swift place the function return type at the right-hand side of the function declaration, rather than the left.

    Swift中的函数将函数返回类型放在函数声明的右侧,而不是左侧。
  • Function parameter declaration syntax is inspired by Objective-C, which is quite different and often at first confusing for Java, C#, and C++ developers.

    函数参数声明语法是受Objective-C启发的,Objective-C完全不同,一开始常常使Java,C#和C ++开发人员感到困惑。
  • The difference between a struct and a class in Swift is similar to what we have in C# (value type versus reference type), but not the same as in C++ (both are the same, except struct members are public by default).

    Swift中的结构和类之间的区别类似于我们在C#中的区别(值类型与引用类型),但与C ++中的不同(两者都相同,除了默认情况下struct成员是公共的)。

Swift程序结构— Hello, World(Swift Program Structure — Hello, World!)

To illustrate the basic structure of a Swift program, let’s create a simple Swift program to display the string Hello, World. to the console:

为了说明Swift程序的基本结构,让我们创建一个简单的Swift程序来显示字符串Hello, World. 到控制台:

[Out:]Hello, World
If you are using Next Tech’s sandbox, you can follow along with the code snippets in this crash course by simply typing in the editor. Otherwise, you can follow along with your own IDE — just make sure that Swift is installed!
如果您使用的是Next Tech的沙箱,则只需在编辑器中键入内容,就可以在此崩溃过程中遵循代码片段。 否则,您可以按照自己的IDE进行操作-只需确保已安装Swift!

Congratulations! In two lines of code, you’ve just written your first fully-functional Swift program.

恭喜你! 用两行代码编写了您的第一个全功能Swift程序。

Now, let’s move on to learning about and using the Swift language — and break down each part of your Hello World program!

现在,让我们继续学习和使用Swift语言-分解Hello World程序的每个部分!

迅捷变量 (Swift Variables)

Virtually all programming languages include the ability for programmers to store values in memory using an associated name chosen by the programmer. Variables allow programs to operate on data values that change during the run of the program.

几乎所有的编程语言都包括程序员使用程序员选择的关联名称将值存储在内存中的功能。 变量允许程序对在程序运行期间更改的数据值进行操作。

A Swift variable declaration uses the following basic syntax:var <variable name> : <type&gt; = <value>

Swift变量声明使用以下基本语法: var <variable name> : <type&g t; = <值>

Given this syntax, a legal declaration for a variable called pi would be:

给定这种语法,称为pi的变量的合法声明为:

This declaration means: “create a variable named pi , which stores a Doubledata type, and assign it an initial value of 3.14159”.

该声明的意思是:“ 创建一个名为pi的变量,该变量存储Double数据类型,并为其分配初始值3.14159 ”。

斯威夫特常数 (Swift Constants)

You may want to store a named value in your program that will not change during the life of the program. How can we ensure that, once defined, this named value can never be accidentally changed by our code? By declaring a constant!

您可能希望在程序中存储一个命名值,该值在程序生命期内不会更改。 我们如何确保一旦定义此命名值,就不会被我们的代码意外更改? 通过声明一个常量

In our earlier Hello, World program, we declared message using let instead of var — therefore, message is a constant.

在我们前面Hello, World程序,我们宣布message使用let ,而不是var因此, - message是一个常数。

Since message was declared as a constant, if we added the following line of code to the end of our program, we would receive a compile-time error, since changing a let constant is illegal:

由于message被声明为常量,因此如果在程序末尾添加以下代码行,则会收到编译时错误,因为更改let常量是非法的:

[Out:]error: cannot assign to value: ‘message’ is a ‘let’ constant

Generally, any time you create a named value that will never be changed during the run of your program, you should use the let keyword to create a constant. The Swift compiler enforces this recommendation by creating a compile-time warning whenever a var is created that is not subsequently changed.

通常,任何时候创建一个在程序运行期间都不会更改的命名值时,都应该使用let关键字创建一个常量。 Swift编译器通过创建编译时警告来强制执行此建议,只要创建了一个随后未更改的var

Other than the restriction on mutating the value of a constant once declared, Swift variables and constants are used in virtually identical ways.

除了在声明常量后更改常量值的限制之外,Swift变量和常量实际上以相同的方式使用。

类型推断 (Type Inference)

In our Hello World example, we created the constant message without specifying its data type. We took advantage of a Swift compiler feature called type inference.

在Hello World示例中,我们创建了常量message但未指定其数据类型。 我们利用了称为类型推断的Swift编译器功能。

When you assign the value of a variable or constant as you create it, the Swift compiler will analyze the right-hand side of the assignment, infer the data type, and assign that data type to the variable or constant you’re creating. For example, in the following declaration, the compiler will create the variable name as a String data type:

当您在创建变量或常量的值时为其赋值时,Swift编译器将分析赋值的右侧, 推断数据类型,然后将该数据类型分配给您正在创建的变量或常量。 例如,在以下声明中,编译器会将变量名称创建为String数据类型:

As a type-safe language, once a data type is inferred by the compiler, it remains fixed for the life of the variable or constant. Attempting to assign a non-string value to the name variable declared above would result in a compile-time error:

作为一种类型安全的语言,一旦编译器推断出数据类型,它在变量或常量的生命周期内将保持不变。 尝试将非字符串值分配给上面声明的name变量将导致编译时错误:

[Out:]error: “cannot assign value of type ‘Double’ to type ‘String’

While Swift is a type-safe language, where variable types are explicit and do not change, it is possible to create Swift code that behaves like a dynamic type language using the Swift Any data type. For example, the following code is legal in Swift:

尽管Swift是一种类型安全的语言,其中变量类型是显式的并且不会更改,但是可以使用Swift Any数据类型创建行为类似于动态类型语言的Swift代码。 例如,以下代码在Swift中是合法的:

While this is legal, it’s not a good Swift programming practice. The Any type is mainly provided to allow bridging between Objective-C and Swift code. To keep your code as safe and error-free as possible, you should use explicit types wherever possible.

尽管这是合法的,但这不是一个好的Swift编程实践。 主要提供Any类型,以允许在Objective-C和Swift代码之间进行桥接。 为了使代码尽可能安全和无错误,应尽可能使用显式类型。

可变命名约定 (Variable Naming Conventions)

Swift variables and constants have the same naming rules as most C-inspired programming languages:

Swift变量和常量与大多数受C语言启发的编程语言具有相同的命名规则:

  • Must not start with a digit

    不能以数字开头
  • After the first character, digits are allowed

    在第一个字符之后,可以使用数字
  • Can begin with and include an underscore character

    可以开头并包含下划线字符
  • Symbol names are case sensitive

    符号名称区分大小写
  • Reserved language keywords may be used as variable names if enclosed in backticks. For example:

    如果保留在反引号中,则保留的语言关键字可用作变量名。 例如:

When creating variable and constant names in Swift, the generally accepted naming convention is to use a camelCase naming convention, beginning with a lowercase letter. Following generally accepted naming conventions makes code easier for others to read and understand.

在Swift中创建变量和常量名称时,通常接受的命名约定是使用camelCase命名约定,以小写字母开头。 遵循公认的命名约定可使其他人更容易阅读和理解代码。

For example, the following would be a conventional variable declaration:

例如,以下是常规变量声明:

However, the following would not be conventional, and would be considered incorrect by many other Swift developers:

但是,以下内容并不常见,许多其他Swift开发人员都认为以下内容不正确:

Unlike many other programming languages, Swift is not restricted to the Western alphabet for its variable name characters. You may use any Unicode character as part of your variable declarations. The following variable declarations are legal in Swift:

与许多其他编程语言不同,Swift的变量名字符不限于西方字母。 您可以将任何Unicode字符用作变量声明的一部分。 以下变量声明在Swift中是合法的:

Note that just because you can use any Unicode character within a variable name, and can use reserved words as variables when enclosed in backticks, it doesn’t mean you should. Always consider other developers who may need to read and maintain your code in the future. The priority for variable names is that they should make code easier to read, understand, and maintain.

请注意,仅因为您可以在变量名中使用任何Unicode字符,并且在反引号内将保留字用作变量时,这并不意味着您应该这样做。 始终考虑将来可能需要阅读和维护您的代码的其他开发人员。 变量名的优先级是它们应使代码更易于阅读,理解和维护。

打印和字符串插值 (Printing and String Interpolation)

In Swift, you can print a variable or a constant to your console using the print() function. Let’s create a variable and a constant and print them out.

在Swift中,您可以使用print()函数将变量或常量print()到控制台。 让我们创建一个变量和一个常量并打印出来。

Execute this snippet in your Code Editor to create a constant named name, and a variable named address:

在代码编辑器中执行此代码段,以创建一个名为name的常量和一个名为address的变量:

[Out:]John Does lives at 201 Main Street

Both name and address store string text. By wrapping the variable or constant name in a pair of parentheses, prefixed by a backslash (\), we are able to print their stored values in a print statement — this is called string interpolation.

nameaddress存储字符串文本。 通过将变量名或常量名包装在一对带有反斜杠( \ )的括号中,我们可以在print语句中打印其存储的值-这称为字符串插值

I hope you enjoyed this quick crash course on the basics of Swift! We learned about basic syntax and program structure, how to declare and use Swift variables and constants, type inference, printing, and string interpolation.

我希望您喜欢这个基于Swift的快速速成课程! 我们学习了基本的语法和程序结构,如何声明和使用Swift变量和常量,类型推断,打印和字符串插值。

If you are interested in learning more about Swift, we have a full Beginning Swift course at Next Tech that you can start for free! In this course we cover:

如果您有兴趣了解有关Swift的更多信息,我们将在Next Tech提供完整的Beginning Swift课程,您可以免费开始学习! 在本课程中,我们涵盖:

  • Other basic programming concepts such as: optionals, tuples, enums, conditionals and loops, methods, structs, and classes.

    其他基本编程概念,例如:可选,元组,枚举,条件和循环,方法,结构和类。

  • Creating scripts and command line applications in Swift

    在Swift中创建脚本和命令行应用程序

  • Using Swift outside of iOS and macOS development lifecycles

    在iOS和macOS开发生命周期之外使用Swift

Happy learning!

学习愉快!

翻译自: https://www.freecodecamp.org/news/learn-swift-basics-in-5-minutes-30a530e23231/

swift3到swift5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值