赞
踩
swift实例教程
In this tutorial we’ll look into the basic syntax of Swift and run it in our console.
在本教程中,我们将研究Swift的基本语法并在控制台中运行它。
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代码,进行实验并在其中玩耍,并在侧栏中看到每一行的结果。
- var a="Hi";
- var a:String="Hi"
指定变量的类型是可选的。 Swift编译器具有一项称为“ 推断类型”的功能,可通过分配的值自动预测变量的类型。 以下两个语句是等效的。 (不以分号结尾也没有任何区别。) 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)")
- }
- let numbersArray = [1, 2, 3]
- var stringArray:[String] = ["Jan", "Feb", "March"]
数组定义如下(类型指定为隐式或显式: stringArray[index_number]
要检索给定索引处的值,我们使用类似于C的形式: stringArray.append("April")
第二个数组是可变的,可以在其中添加新元素。 append方法用于在其中添加新元素。 以下代码段演示了相同的内容。 stringArray.insert("Dec", atIndex: 1)
要在特定索引而不是末尾附加新元素,将使用insert方法,如下所示。 stringArray[1..<3] = ["2","3","4"]
The above statement implies, inclusive of the startIndex and exclusive of the endIndex
上面的语句隐含了startIndex和endIndex
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 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"]
A switch condition loop is a bit different in Swift than what we’ve seen till now.
Swift中的开关条件循环与我们到目前为止所见的有所不同。
fallthrough
keyword. 不需要break语句。 相反,如果要转到下一种情况,则使用fallthrough
关键字。 - let x=5
-
- switch 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也会打印下一条语句
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" {}
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枚举,该枚举作为函数中的参数传递。
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实例教程
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。