swift实例教程

In this tutorial we’ll look into the basic syntax of Swift and run it in our console.

在本教程中,我们将研究Swift的基本语法并在控制台中运行它。

总览 (Overview)

Click Get started with a playground. A playground is a new type of file that allows us to test out Swift code, experiment and play around with it and see the results of each line in the sidebar.

单击“开始使用游乐场”。 游乐场是一种新型文件,它使我们可以测试Swift代码,进行实验并在其中玩耍,并在侧栏中看到每一行的结果。

变量和常量 (Variables and Constants)

  1. Variables are declared using the keyboard var that stands for variable使用代表变量的键盘var声明变量
  2. Specifying the type of variable is optional. Swift compiler has a feature called Inferred Typing to automatically predict the type of variable by the value assigned. Both of the below statements are equivalent. (Not ending with a semi-colon doesn’t make any difference too.)
    var a="Hi";
    var a:String="Hi"

    指定变量的类型是可选的。 Swift编译器具有一项称为“ 推断类型”的功能,可通过分配的值自动预测变量的类型。 以下两个语句是等效的。 (不以分号结尾也没有任何区别。)

  • To define a constant the declaration must start with a let keyword. Assigning a different value to the same variable will give rise to compile time error要定义常量,声明必须以let关键字开头。 为同一变量分配不同的值将导致编译时错误
  • The types that can be assigned to variables are- Int, Float, Double, Bool, String可以分配给变量的类型是-Int,Float,Double,Bool,String
  • 条件语句和字符串插值 (Conditional Statements and String Interpolation)

    In swift there is no need to put parentheses in the if-else conditions. This leads to better readability.
    A String Interpolation is a simple way of combining variables and constants inside a string.

    快速地,不需要在if-else条件下加上括号。 这导致更好的可读性。
    字符串插值是在字符串内组合变量和常量的简单方法。

    print("This is the first Swift Tutorial. "+"\(a)")

    The above snippet prints out the string to the console. It contains a string variable appended to the string as it’s seen above.

    上面的代码片段将字符串打印到控制台。 如上面所见,它包含一个附加到字符串的字符串变量。

    An example using the if-else with String interpolation is given below.

    下面给出了使用if-else和String插值的示例。

    var i=1;
    let j=2;if i<j {
    print("If statement is executed i and j are "+"\(i) "+"\(j)")
    }
    else{
    print("Else statement is executed i and j are "+"\(i) "+"\(j)")
    }

    数组和For循环 (Arrays and For loops)

    1. Arrays are defined as follows (type is specified either implicit or explicit :

      let numbersArray = [1, 2, 3]
      var stringArray:[String] = ["Jan", "Feb", "March"]

      数组定义如下(类型指定为隐式或显式:

    2. To retrieve the value at a given index we use the form similar to that in C :
      stringArray[index_number]

      要检索给定索引处的值,我们使用类似于C的形式:

    3. The second array is mutable new elements can be added in it. the append method is used to add a new element in it. The following snippet demonstrates the same.
      stringArray.append("April")

      第二个数组是可变的,可以在其中添加新元素。 append方法用于在其中添加新元素。 以下代码段演示了相同的内容。

    4. To append a new element at a specific index instead of at the end, the insert method is used as shown below.
      stringArray.insert("Dec", atIndex: 1)

      要在特定索引而不是末尾附加新元素,将使用insert方法,如下所示。

    5. To assign different values to a range of indexes of an array we use the following syntax.
      stringArray[1..<3] = ["2","3","4"]

      The above statement implies, inclusive of the startIndex and exclusive of the endIndex

      上面的语句隐含了startIndex和endIndex

    6. To merge two arrays into one. We use the + operator
      var both = stringArray + stringArray

      将两个数组合并为一个。 我们使用+运算符

    For loop in a Swift is similar to that in Objective-C except the fact that no parentheses are needed. The more recommended approach is the fast enumeration one. It’s given below.

    Swift中的for循环与Objective-C中的类似,除了不需要括号的事实。 推荐的方法是快速枚举。 它在下面给出。

    for s in stringArray {print("String is "+"\(s)")
    }

    The classic old approach is to iterate over the elements using the count static method over the array. It’s given below.

    经典的旧方法是使用count静态方法遍历数组来遍历元素。 它在下面给出。

    for i in 0..<stringArray.count {let p = stringArray[i]print("String is "+"\(p)")
    }

    The < operator is a non-inclusive range operator and doesn’t include the upper bound value.

    <运算符是一个非包含范围的运算符,不包括上限值。

    辞典 (Dictionaries)

    Dictionaries are another collection type that go a step ahead from Arrays in the fact that they let us access values based on the specific keys we specify. They are useful when we need to access an element from a value other than the standard identifier. The code snippet below shows how it’s declared and how the elements are accessed.

    字典是另一种集合类型,它比Array领先,因为它们使我们可以根据指定的特定键访问值。 当我们需要从标准标识符以外的值访问元素时,它们很有用。 下面的代码片段显示了如何声明它以及如何访问元素。

    var person = ["month": "April", "language": "Swift", "website": "journaldev.com"]
    person["language"]

    Note: If the key entered doesn’t exist. Then a nil would be returned. Try it out.

    注意:如果输入的密钥不存在。 然后将返回零。 试试看。

    Explicitly specifying the type is done like this:

    明确指定类型是这样的:

    var dict2: Dictionary<Int, String> = [1:"1",2:"2"]

    切换语句 (Switch Statements)

    A switch condition loop is a bit different in Swift than what we’ve seen till now.

    Swift中的开关条件循环与我们到目前为止所见的有所不同。

    1. A break statement is not needed. On the contrary if we want to go to the next case we use a fallthrough keyword.不需要break语句。 相反,如果要转到下一种情况,则使用fallthrough关键字。
    2. A single case can check for more than one values by specifying the range in the case. An example is given below.
      let x=5switch x {
      case 0...1:print("This is printed for the range 0 to 1 inclusive")case 2...4:print("This is printed for the range 2 to 4 inclusive")case 5...8:print("This is printed for the range 5 to 8 inclusive")fallthrough
      default:print("Default is only needed when cases are not exhaustive. Else compile time error will come.")
      }

      In the above code, fallthrough would print the next statements as well

      在上面的代码中, fallthrough也会打印下一条语句

    3. The default statement isn’t needed if the cases cover all the possibilities. But if there is a case not covered then the default statement is a must, else compile time error would occur.如果案例涵盖所有可能,则不需要默认语句。 但是,如果有没有解决的情况,则默认语句是必须的,否则会发生编译时错误。

    功能 (Functions)

    Functions are reusable pieces of codes that can be invoked and run anywhere once defined. They begin with the letter func.

    函数是可重用的代码,可以在定义后在任何地方调用和运行。 他们以字母func开头。

    A basic example of a user defined function is given below.

    用户定义功能的基本示例如下。

    func firstFunction() {print("A basic function")
    }

    The above statement will only be executed when the firstFunction() is called.

    上面的语句仅在调用firstFunction()时执行。

    The syntax when a function has a return type is given below along with an example.

    下面给出了函数具有返回类型时的语法以及示例。

    func thisReturns(name: String) -> Bool {if name == "JournalDev" { return true }return false
    }if thisReturns("JournalDev") {print("True is returned")
    }

    Swift gives us the liberty to make a return type optional by appending a “?” at the end of it.

    Swift通过添加“?”赋予我们自由选择返回类型的自由 在它的结尾。

    func thisReturns(name: String) -> Bool" {}

    枚举 (Enumerations)

    Swift is one language that has made enums powerful than before. We can define our own data types using enums and pass them in functions. An example is given below.

    Swift是一种使枚举比以前强大的语言。 我们可以使用枚举定义自己的数据类型并将其传递给函数。 下面给出一个例子。

    enum MoodType {case Happy, Sad, Worried, Tensed, Angry
    }func getMood(mood: MoodType) -> String? {if mood == MoodType.Happy {return nil} else {return "Something is wrong with your mood today!"}
    }getMood(.Sad)

    We’ve defined a MoodType enum that’s passed as a parameter in the function.

    我们定义了一个MoodType枚举,该枚举作为函数中的参数传递。

  • Note: MoodType.Happy is same as .Happy since Swift uses type inferencing to detect the type of the data. This is evident in the code when we’ve called that function.注意:MoodType.Happy与.Happy相同,因为Swift使用类型推断来检测数据的类型。 当我们调用该函数时,这在代码中显而易见。
  • A quick look at our playground with almost all the above code snippets compactly placed is given below.

    快速浏览一下我们的操场,上面几乎所有代码片段都紧凑地放置在下面。

    In this tutorial we’ve covered the basic Swift syntax with examples. We’ll cover the more complex stuff in the iOS Tutorials.

    在本教程中,我们通过示例介绍了基本的Swift语法。 我们将在iOS教程中介绍更复杂的内容。

    翻译自: https://www.journaldev.com/10582/fundamentals-of-swift-example-tutorial

    swift实例教程

swift实例教程_Swift示例教程基础相关推荐

  1. jaxb教程_JAXB示例教程

    jaxb教程 Welcome to JAXB Example Tutorial. Java Architecture for XML Binding (JAXB) provides API for c ...

  2. angularjs 实例_AngularJS服务示例教程

    angularjs 实例 Today we will look at one of the important angular concepts called AngularJS Services. ...

  3. angularjs 实例_AngularJS包含示例教程

    angularjs 实例 Earlier we looked at custom directives and in this tutorial, we will discuss about the ...

  4. angularjs 实例_AngularJS过滤器示例教程

    angularjs 实例 We looked at View Model, View and Controller concepts in the previous post. Now we are ...

  5. jsf入门实例_JSF selectManyListBox示例教程

    jsf入门实例 JSF allows users to select multiple values for a single field with the help of <h:selectM ...

  6. 帆软单选按钮实例_HTML单选按钮示例教程

    帆软单选按钮实例 In the old times, radios have some buttons to change stations that have saved to a specific ...

  7. android实例教程_改造Android示例教程

    android实例教程 Welcome to Retrofit Android Example Tutorial. Today we'll use the Retrofit library devel ...

  8. Parse 教程:网络后台基础

    Parse 教程:网络后台基础 2015-07-21 10:07 编辑: suiling 分类:iOS开发 来源:Raywenderlich 本文由CocoaChina翻译组成员leon(社区ID)翻 ...

  9. Hibernate Validator JSR303示例教程

    Hibernate Validator JSR303示例教程 欢迎使用Hibernate Validator示例教程.数据验证是任何应用程序的组成部分.您将使用Javascript在表示层找到数据验证 ...

最新文章

  1. RxJava 教程第一部分:为何使用RxJava
  2. @Builder(toBuilder=true) 链式初始化对象、修改对象
  3. java 判断请求为 ajax请求_请问如何判断一个请求是不是ajax请求?
  4. Matlab与simulink中的数据类型
  5. eclipse导入项目中文乱码
  6. 从高排到低变成小楼梯儿歌_幼儿早教三字儿歌,帮助宝宝启蒙学说话
  7. node.js学习之npm 入门 —8.《怎样创建,发布,升级你的npm,node模块》
  8. easy datagrid 按钮控制
  9. 20210311 plecs to file 功能
  10. 基于Pytorch的YoLoV4模型代码及作品欣赏
  11. CF 1437C Chef Monocarp (背包dp)
  12. sql根据出生日期算年龄
  13. 数学运算符“异或”的妙用
  14. 2021/9/12正睿10测Day.3
  15. 降噪蓝牙耳机推荐什么牌子好?入耳式降噪蓝牙耳机推荐
  16. 使用Python进行立体几何和立体校正的综合教程
  17. pytorch中nn.moudle模块
  18. 人脸对齐(Face Alignment)
  19. Keynote怎么转换为PPT/PDF
  20. GitHub Desktop使用说明(2)快捷键

热门文章

  1. php中0, ,null和false的区别
  2. [转]memcached+magent实现memcached集群
  3. C++ 类的静态成员详细讲解(转)
  4. android (java) 网络发送get/post请求参数设置
  5. 操作系统和语言的关系(转载)
  6. [转载] numpy教程:矩阵matrix及其运算
  7. Flask 框架中 上下文基础理念,包括cookie,session存储方法,requset属性,current_app模块和g模块...
  8. lua系列之 lua-cjson模块安装报错问题解决
  9. java 通过eclipse编辑器用mysql尝试 连接数据库
  10. 浅谈es6 promise