swift简介_Swift简介

swift简介

Clear examples to demonstrate the basics.

清晰的示例说明基本知识。

涵盖的主题 (Topics Covered)

  1. Variables

    变数
  2. Data Types

    资料类型
  3. Optional Values

    可选值
  4. Collections

    馆藏
  5. For-In Loops

    循环内
  6. Functions

    功能

变量-Var vs Let (Variables — Var vs Let)

Declaring a variable in swift is easy.

快速声明变量很容易。

var name = "Wallace"

Here we are assigning the value of “Wallace” to a variable called name .

在这里,我们将“Wallace”的值分配给名为name的变量。

Using var informs us that the variable is mutable. A mutable variable is one that can have its value changed after creation.

使用var通知我们变量是可变的 。 可变变量是在创建后可以更改其值的变量。

name = "Gromit"

The variable name now only holds a reference to the value "Gromit" . The reference to "Wallace" has been lost.

现在,变量name仅保留对值"Gromit"的引用。 对"Wallace"的引用已丢失。

Like many programming languages, Swift supports the notion of immutability. To declare an immutable variable, we use the keyword let .

像许多编程语言一样,Swift支持不变性的概念 要声明一个不可变的变量,我们使用关键字let

let neverChange = true

Let’s see what happens if we try to change its value.

让我们看看如果尝试更改其值会发生什么。

Image for post
Xcode Playground
Xcode游乐场

Xcode gives us a clear error, informing of our invalid assignment.

Xcode给我们一个明显的错误,告知我们无效的分配。

You should use let when you are certain that the variable does not need to be changed in the future. Doing this will reduce the time you spend debugging your code for variables that have been misassigned to new values.

当您确定将来不需要更改该变量时,应使用let 。 这样做将减少您花在调试代码上的错误代码上的时间。

资料类型 (Data Types)

Included in the basic data types for Swift are the following:

Swift的基本数据类型包括以下内容:

  • Int: An integer value which can be either positive or negative.

    Int:可以为正或负的整数值。

  • Float: A decimal number which can be either positive or negative.

    浮点数:十进制数字,可以是正数或负数。

  • Bool: A boolean value which can be either true of false.

    布尔值布尔值,可以为truefalse

  • String: Used to represent textual information.

    字符串:用于表示文本信息。

When we assigned the value "Wallace" to the variable name , in the background, Swift inferred that the data type was a string.

当我们在后台将值"Wallace"分配给变量name ,Swift推断数据类型为字符串。

This can be demonstrated by printing the type of name as follows:

可以通过如下打印name类型来证明这一点:

Image for post
Xcode Playground
Xcode游乐场

We can explicitly state the data type of a variable by adding :DataType before the assignment operator =.

我们可以通过在赋值运算符=之前添加:DataType来显式声明变量的数据类型。

The following two lines are identical in meaning.

以下两行含义相同。

var name = "Wallace"
var explicitName:String = "Wallace"

Once the data type of a variable has been assigned, you cannot assign values of different data types. Trying to do so gives us the following error.

分配变量的数据类型后, 就无法分配其他数据类型的值。 尝试这样做会给我们带来以下错误。

Image for post
Xcode Playground
Xcode游乐场

选装件 (Optionals)

Values can be declared as optional by placing a ? after the type.

可以通过放置?将值声明为可选值? 类型之后。

var optionalInt:Int? = 1

Optional values may take either of two states:

可选值可以采用以下两种状态之一:

  1. nil — Indicating that the value is missing.

    nil —指示缺少值。

  2. The Value — The actual value corresponding to the data type, e.g an Int.

    值-与数据类型相对应的实际值,例如Int。

When using an optional, we want to check if its value is nil beforehand. There are a few ways to do this.

使用可选时,我们要事先检查其值是否为nil 。 有几种方法可以做到这一点。

等号运算符(==和!=) (Equality Operators (== and !=))

var optionalString:String?if(optionalString == nil){
print("The value is nil")
}

The above code outputs "The value is nil" because the variable optionalString has been declared to have an optional value but the value is missing.

上面的代码输出"The value is nil"因为已声明变量optionalString具有可选值,但缺少该值。

var optionalString:String? = "Hey"if(optionalString != nil){
print(optionalString)
}

The above code outputs "Hey" . Instead of checking if the value is equal to nil, we are checking if the value is not equal to nil by using != .

上面的代码输出"Hey" 。 而不是检查,如果该值等于零的,我们正在检查,如果该值使用等于零!=

可选装订 (Optional Binding)

var optionalDog:String? = "Gromit"if let dog = optionalDog{
print(dog)
}

The above code outputs "Gromit" . The value optionalDog is checked. If it is not nil then its value is assigned the variable dog . The variable dog can then be used inside the if-statement.

上面的代码输出"Gromit" 。 值optionalDog已选中。 如果不是 nil,则将其值分配给变量dog 。 然后可以在if语句内使用变量dog

If the value of optionalDog is nil, the code inside the if-statement is ignored.

如果optionalDog值为nil,则if语句中的代码将被忽略。

var optionalDog:String?if let dog = optionalDog{
print(dog)
}

The above code does not output anything.

上面的代码不输出任何内容。

强制展开 (Forced Unwrapping)

If it known for certain that the value of an optional variable is not nil, you can force the unwrapping of its value by using the operator ! . This lets us use the value without checking if the value is present.

如果可以确定某个可选变量的值不是nil,则可以使用运算符来强制展开其值! 。 这使我们无需检查该值是否存在就可以使用该值。

var optional:Int? = 1
print(optional!)

The above code outputs 1 .

上面的代码输出1

This, however, will cause your program to crash if you force the unwrapping of nil.

但是,如果强制展开nil,这将导致程序崩溃。

Image for post
Xcode Playground
Xcode游乐场

馆藏 (Collections)

Two of the primary collection types in Swift are Arrays and Dictionaries.

Swift中两个主要的集合类型是数组和字典。

数组 (Array)

Arrays store data of the same type in an ordered list.

数组将相同类型的数据存储在有序列表中。

The following code creates an empty Array which stores Strings.

以下代码创建一个空数组,用于存储字符串。

var listOfStrings = [String]()

If we want to let Swift infer the type of our Array, we can create it and populate it with some entries as follows:

如果我们想让Swift推断数组的类型,我们可以创建它并用一些条目填充它,如下所示:

var someStrings = ["Wallace", "Gromit", "Cheddar"]

The items inside of an Array are accessed via indexes. The index represents its position in the array. We always start the count from 0.

数组内部的项目可通过索引访问。 索引表示其在数组中的位置。 我们总是从0开始计数。

var someStrings = ["Wallace", "Gromit", "Cheddar"]
print(someStrings[1])

The above code outputs "Gromit" .

上面的代码输出"Gromit"

字典 (Dictionary)

Dictionaries store unordered key-value pairs, where all keys are of the same type and all values are of the same type.

字典存储无序的键值对,其中所有键都属于同一类型,所有值都属于同一类型。

We can create an empty dictionary which maps from String keys to Int values as follows:

我们可以创建一个空字典,该字典将String键映射为Int值,如下所示:

var romanToDecimal = [String: Int]()

And now to create some mappings we can do the following:

现在,要创建一些映射,我们可以执行以下操作:

romanToDecimal["X"] = 10
romanToDecimal["V"] = 5

A Note on Performance

性能说明

Dictionaries provide instant look-up time. If we want to check if a key is present in a dictionary, all we do is check if there is a mapping for the key to a value. In big O notation, a notation used to describe the worst-case runtime of a piece of code, we would write this as O(1).

词典提供即时查找时间。 如果要检查字典中是否存在键,我们要做的就是检查键是否存在到值的映射。 在大O表示法中 ,一种用于描述一段代码的最坏情况运行时的表示法,我们将其写为O(1)。

If we want to check if a value is present in an array, we need to cycle through the array and examine each element individually. In big O, it is written as O(n). This is to say that our runtime is bounded by the number of elements (n) in the array.

如果要检查数组中是否存在值,则需要遍历数组并分别检查每个元素。 在大O中,它写为O(n) 也就是说,我们的运行时受数组中元素(n)的数量限制。

变异性 (Mutability)

Assigning a collection to a variable means that the collection can be changed later on.

将集合分配给变量意味着可以稍后更改集合。

var someList = [1,2,3]
someList = [1]

If instead, the collection is assigned to a constant, the collection and its contents cannot be changed.

相反,如果将集合分配给常量,则不能更改集合及其内容。

Image for post

循环内 (For-In Loop)

We can easily iterate over the elements of an array using a for-in loop.

我们可以使用for-in循环轻松地迭代数组的元素。

var nums = [1,2,3]for num in nums{
print(num)
}"""
Output:
1
2
3
"""

The above code prints each of the values in nums separately.

上面的代码分别打印以nums为单位的每个值。

If we want to have access to the value and its index, we can use enumerated.

如果我们想访问该值及其索引,则可以使用enumerated。

var nums = [1,2,3]for (index,nums) in nums.enumerated(){
print(index,nums)
}"""
Output:
0 1
1 2
2 3
"""

If we need to create a for loop in the range of two numbers, we can have two choices at our disposal:..< and ... .

如果我们需要在两个数字范围内创建一个for循环,则可以使用两个选择: ..<...

Using ..< excludes the right-most value.

使用..<排除最右边的值。

for i in 0..<3 {
print(i)
}"""
Output:
0
1
2
"""

Using ... includes the right-most value.

使用...包括最右边的值。

for i in 0...3 {
print(i)
}"""
Output:
0
1
2
3
"""

功能 (Functions)

Functions are reusable blocks of code which perform specific tasks. They are defined using the keyword func .

函数是执行特定任务的可重用代码块。 它们是使用关键字func定义的。

Functions may take a list of arguments in parenthesis and may specify the data type of the return value. The return type is declared after the argument-parenthesis by using the operator -> .

函数可以带括号的参数列表,并可以指定返回值的数据类型。 通过使用运算符->在参数括号之后声明返回类型。

The following function addTwoNumbers takes two parameters x and y, both of type Int . The function returns the sum of x and y as an Int type.

以下函数addTwoNumbers具有两个参数xy ,均为Int类型。 该函数以Int类型返回x和y的和。

func addTwoNumbers(x:Int, y:Int) -> Int {
return x + y
}let z = addTwoNumbers(x: 5, y: 10)
print(z)"""
Output:
15
"""

结语 (Wrapping up)

That concludes my demonstration for some of the essentials of Swift.

到此为止,我完成了对Swift某些基本知识的演示。

If you want to build on your swift knowledge with a working IOS example, I recommend this set of tutorials by Apple.

如果您想通过一个有效的IOS示例来快速掌握知识,我建议使用Apple提供的这套教程。

Thank you for reading 🙏

谢谢您阅读🙏

Stay safe.

注意安全。

翻译自: https://medium.com/the-dev-café/an-introduction-to-swift-9f75fe193eec

swift简介

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值