快看Sample代码,速学Swift语言(2)-基础介绍

Swift语言是一个新的编程语言,用于iOS, macOS, watchOS, 和 tvOS的开发,不过Swift很多部分内容,我们可以从C或者Objective-C的开发经验获得一种熟悉感。Swift提供很多基础类型,如Int,String,Double,Bool等类型,它和Objective-C的相关类型对应,不过他是值类型,而Objective-C的基础类型是引用类型,另外Swift还提供了几个集合类型,如ArraySet, 和 Dictionary;Swift引入一些Objective-C里面没有的元祖类型,这个在C#里倒是有类似的,也是这个名词。 Swift语言是一种类型安全的强类型语言,不是类似JavaScript的弱类型,能够在提供开发效率的同时,减少常规出错的可能,使我们在开发阶段尽量发现一些类型转换的错误并及时处理。

常量和变量


1

2

let maximumNumberOfLoginAttempts 10

var currentLoginAttempt 0

 常量用let定义,变量用var定义,它们均可以通过自动推导类型,如上面的就是指定为整形的类型。

也可以通过逗号分开多个定义,如下所示


1

var x 0.0y 0.0z 0.0

 如果我们的变量没有初始化值来确定它的类型,我们可以通过指定类型来定义变量,如下所示


1

2

3

var welcomeMessageString

 

var redgreenblueDouble

 变量的打印,可以在输出字符串中用括号包含变量输出,括号前加斜杠 \ 符号。

print(friendlyWelcome)
// Prints "Bonjour!"

print("The current value of friendlyWelcome is \(friendlyWelcome)")
// Prints "The current value of friendlyWelcome is Bonjour!"

注释符


1

2

3

4

5

6

7

8

// This is a comment.

 

/* This is also a comment

 but is written over multiple lines. */

 

/* This is the start of the first multiline comment.

 /* This is the second, nested multiline comment. */

 This is the end of the first multiline comment. */

 上面分别是常规的的注释,以及Swift支持嵌套的注释符号

分号

Swift语句的划分可以不用分号,不过你加分号也可以,如果加分号,则可以多条语句放在一行。


1

let cat ""print(cat)

 

整型

let minValue = UInt8.min  // minValue is equal to 0, and is of type UInt8
let maxValue = UInt8.max  // maxValue is equal to 255, and is of type UInt8

一般情况下,我们不需要指定具体的Int类型,如Int32,Int64,我们一般采用int类型即可,这样可以在不同的系统平台有不同的意义。

在32位平台,Int代表是Int32

在64位平台,Int代表Int64

浮点数字

Swift的浮点数字类型包括有Float(单精度)和Double(双精度)两个类型,Float代表32位浮点数字,Double代表64位浮点数字。

默认通过小数值推导的变量或者常量的类型是Double,而非Float。

数字文字


1

2

3

4

let decimalInteger 17

let binaryInteger 0b10001       // 17 二进制

let octalInteger 0o21           // 17 八进制

let hexadecimalInteger 0x11     // 17 十六进制


1

2

3

let decimalDouble 12.1875

let exponentDouble 1.21875e1  //科学计数法 1.21875*10

let hexadecimalDouble 0xC.3p0 // p0代表 2的0次方

 上面是科学计数方式的几种方式


1

2

3

let paddedDouble 000123.456

let oneMillion 1_000_000

let justOverOneMillion 1_000_000.000_000_1

 上面是使用0代替补齐签名数字,以及下划线来标识数字分割,方便阅读


1

2

3

let three 3

let pointOneFourOneFiveNine 0.14159

let pi Double(three) + pointOneFourOneFiveNine

 常量 three 初始化位整形类型, pointOneFourOneFiveNine 推导为Double类型,而pi则通过Double转换推导为Double类型,这样右边两个都是Double类型,可以进行相加的运算处理了。

布尔类型


1

2

let orangesAreOrange true

let turnipsAreDelicious false

 这个没有什么好讲的,就是语言默认有布尔类型提供,相对于Objective-C的非0则为True而言,布尔类型只有两个字,True或者False。

布尔类型可以用于条件判断等处理,如下


1

2

3

4

5

if turnipsAreDelicious {

    print("Mmm, tasty turnips!")

else {

    print("Eww, turnips are horrible.")

}

元祖类型

元祖类型就是组合多个值的一个对象类型,在组合中的类型可以是任何Swift的类型,而且不必所有的值为相同类型。


1

2

let http404Error = (404"Not Found")

// http404Error is of type (Int, String), and equals (404, "Not Found")

 另外可以解构对应的元祖类型的值到对应的常量或者变量里面,如下代码


1

2

3

4

5

let (statusCodestatusMessage) = http404Error

print("The status code is \(statusCode)")

// Prints "The status code is 404"

print("The status message is \(statusMessage)")

// Prints "The status message is Not Found"

 也可以通过下划线来忽略相关的值,如下


1

2

let (justTheStatusCode_) = http404Error

print("The status code is \(justTheStatusCode)")

 元祖对象里面的值可以通过数字索引来引用,如0,1的属性,如下


1

2

3

4

print("The status code is \(http404Error.0)")

// Prints "The status code is 404"

print("The status message is \(http404Error.1)")

// Prints "The status message is Not Found"

可空类型

这个和C#里面的可空类型是对应的,也就是对象可能有值,也可能没有值

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber 推导类型为 "Int?", 或者 "optional Int"

Int类型的构造函数为可空构造函数,有可能转换失败,因此返回的为可空Int类型

可空类型可以通过设置nil,来设置它为无值状态


1

2

3

4

var serverResponseCodeInt? = 404

// serverResponseCode contains an actual Int value of 404

serverResponseCode nil

// serverResponseCode now contains no value

 对于可空类型,如果确认它的值非空,那么可以强行解构它的值对象,访问它的值在变量后面增加一个!符号,如下所示


1

2

3

if convertedNumber != nil {

    print("convertedNumber has an integer value of \(convertedNumber!).")

}

 一般情况下,我们可以通过可空绑定的方式来处理这种对象的值,语句语法如下所示


1

2

3

if let constantName someOptional {

    statements

}

 具体的语句如下所示


1

2

3

4

5

6

if let actualNumber Int(possibleNumber) {

    print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")

else {

    print("\"\(possibleNumber)\" could not be converted to an integer")

}

// Prints ""123" has an integer value of 123"

 也可以多个let的可空绑定语句一起使用


1

2

3

4

5

6

7

8

9

10

11

12

13

if let firstNumber Int("4"), let secondNumber Int("42"), firstNumber < secondNumber && secondNumber < 100 {

    print("\(firstNumber) < \(secondNumber) < 100")

}

// Prints "4 < 42 < 100"

  

if let firstNumber Int("4") {

    if let secondNumber Int("42") {

        if firstNumber < secondNumber && secondNumber < 100 {

            print("\(firstNumber) < \(secondNumber) < 100")

        }

    }

}

// Prints "4 < 42 < 100"

解包可空类型可以通过!符号进行处理,一般情况如下所示进行判断


1

2

3

4

5

let possibleStringString? = "An optional string."

let forcedStringString possibleString// requires an exclamation mark

  

let assumedStringString! = "An implicitly unwrapped optional string."

let implicitStringString assumedString // no need for an exclamation mark

 也可以使用可空绑定的let 语句进行隐式的解包,如下所示


1

2

3

4

if let definiteString assumedString {

    print(definiteString)

}

// Prints "An implicitly unwrapped optional string."

错误处理

函数抛出异常,通过在函数里面使用throws进行声明,如下


1

2

3

func canThrowAnError() throws {

    // this function may or may not throw an error

}

 捕捉函数抛出的异常代码如下


1

2

3

4

5

6

do {

    try canThrowAnError()

    // no error was thrown

catch {

    // an error was thrown

}

 详细的案例代码如下所示


1

2

3

4

5

6

7

8

9

10

11

12

func makeASandwich() throws {

    // ...

}

  

do {

    try makeASandwich()

    eatASandwich()

catch SandwichError.outOfCleanDishes {

    washDishes()

catch SandwichError.missingIngredients(let ingredients) {

    buyGroceries(ingredients)

}

断言调试

Swift提供一些标准库函数来进行断言调试,分为断言和预设条件的处理两部分。

断言调试仅仅在Debug调试模式运行,而预设条件则是调试模式和产品发布后都会运行的。


1

2

3

let age = -3

assert(age >0"A person's age can't be less than zero.")

// This assertion fails because -3 is not >= 0.


1

2

3

4

5

6

7

if age > 10 {

    print("You can ride the roller-coaster or the ferris wheel.")

else if age > 0 {

    print("You can ride the ferris wheel.")

else {

    assertionFailure("A person's age can't be less than zero.")

}

 预设条件代码如下,用来对一些条件进行校验


1

2

// In the implementation of a subscript...

precondition(index > 0"Index must be greater than zero.")

本文转自博客园伍华聪的博客,原文链接:快看Sample代码,速学Swift语言(2)-基础介绍,如需转载请自行联系原博主。

时间: 2024-08-03 03:37:00

快看Sample代码,速学Swift语言(2)-基础介绍的相关文章

快看Sample代码,速学Swift语言(1)-语法速览

Swift是苹果推出的一个比较新的语言,它除了借鉴语言如C#.Java等内容外,好像还采用了很多JavaScript脚本里面的一些脚本语法,用起来感觉非常棒,作为一个使用C#多年的技术控,对这种比较超前的语言非常感兴趣,之前也在学习ES6语法的时候学习了阮一峰的<ECMAScript 6 入门>,对JavaScript脚本的ES6语法写法叹为观止,这种Swift语言也具有很多这种脚本语法的特点,可以说这个Swift在吸收了Object C的优点并摒弃一些不好的东西外,同时吸收了大量新一代语言的

c语言-C++代码改成C语言代码,没学过C++好多看不懂啊(泪奔······)求大神指点,我用的VC6.0

问题描述 C++代码改成C语言代码,没学过C++好多看不懂啊(泪奔······)求大神指点,我用的VC6.0 代码如下, #include "winsock2.h" #include "Winsnmp.h" #include 这里是string以下都要用 < 和 > 括起来(不知为何不显示=,=) #include vector #include algorithm #include iostream #pragma comment(lib,"

c语言acm1003 求大神看看我的代码哪错了

问题描述 c语言acm1003 求大神看看我的代码哪错了 Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14. Input The first line of the input

有人懂fortran语言吗?可以帮我看下代码,写成c语言吗?十分感谢!

问题描述 有人懂fortran语言吗?可以帮我看下代码,写成c语言吗?十分感谢! FUNCTION XTERP(XCC,X,Y,NDEG,NPTS,DINT,IER) XTR 0001 C XTR 0002 C FUNCTION PERFORMS NEWTONS INTERPOLATION FOR DISCRETE DATA XTR 0003 C AS A FUNCTION OF ONE VARIABLE XTR 0004 C XTR 0005 C WHERE XC - INDEPENDENT

刚学c语言出了小问题。。大神棒棒看 谢谢

问题描述 刚学c语言出了小问题..大神棒棒看 谢谢 一个计算日期距离的玩意 #include int sr(); int main() { printf("请输入起始年月日(以回车间隔) "); int memories; int year = sr(); int month = sr(); int day = sr(); printf("请输入当前年月日(以回车间隔) "); int thisyear = sr(); int thismonth = sr(); i

char-大侠快看我写的一小段代码

问题描述 大侠快看我写的一小段代码 #include #include //搜索x44x65x73x63x72x69x70x74x69x6Fx6E 偏移地址 DWORD ReadFile(char* str) { char data[11] = {0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6F, 0x6E}; HANDLE pfile = CreateFile(str,GENERIC_READ,0,NULL,OPEN_EXIS

图片-刚学c语言,各位大大帮我看看这段代码哪里有错,谢谢啦

问题描述 刚学c语言,各位大大帮我看看这段代码哪里有错,谢谢啦 题目是判断一个数是否能被3整除 解决方案 第一,主函数里调用函数方法即可,不可以定义函数:第二,你的函数名不规范,一般很少用一个单字母表示函数,当然f除外(习惯不好),可以命名为Divide_3.第三,返回值最好用宏定义设计为True或者False,逻辑更清晰. 解决方案二: main函数中调用x()函数#include int main(){x(s);}int x(int s){....} 解决方案三: 这个太基础了,你应该多看点

编程语言 office-输出word或者excel表格,学什么语言比较快能上手?

问题描述 输出word或者excel表格,学什么语言比较快能上手? 因为工作需要,想编写一个程序,实现自动生成excel或者word表格的功能(主要是一些预算表之类的,单价可以现成的查,大概的思路就是在软件页面输入名称.数量之类的信息,之后自动生成一个价格统计表,可以是excel,也可以是word的表格),对于编程没有多少基础,只是在大学学过一本谭浩强的C语言,后来学了一点C++,想问下各位达人,要实现这个功能学什么语言能相对比较快.比较容易的上手实现?或者还是接着学c++ ?本身不是因为爱编程

c语言-初学者学C语言看书遇到的问题

问题描述 初学者学C语言看书遇到的问题 if(c>='Z'&&c<='Z'+4||c>'z') //书上写的是用这句话判断c是否是26个字母的后4个之一 想请大家讲解一下,初学者,着实没看懂,为什么不写成 if((c>='W'&&'c'<='Z')||(c>='w'&&'c'<='z')) 解决方案 估计是这个"后四个之一"理解错了,书上的意思是:Z字幕后面的4个(Z的后面四个):而你的意思是26