没有合适的资源?快使用搜索试试~ 我知道了~
首页Apple发布革新语言Swift:面向iOS/OSX开发的现代与安全编程新体验
Swift是由Apple公司为iOS和OS X平台设计的一款全新编程语言,旨在提升开发效率和体验。它的诞生是对C和Objective-C这两种在iOS开发中广泛应用的语言的扩展,但不受C兼容性限制,从而能够引入更安全、灵活和有趣的编程特性。Swift的设计理念是借鉴Objective-C的易读性,并在此基础上引入现代编程范式,如安全的编程模式和自动引用计数(ARC)来简化内存管理。
Swift的开发过程历时多年,Apple在原有编译器、调试器以及框架基础设施上进行了优化和升级。Objective-C本身也进行了相应的革新,如支持块、集合字面量和模块化,使得框架可以无缝接纳现代语言技术,而不会造成混乱。这种坚实的基础为Swift的推出打下了坚实的基础。
对于Objective-C开发者来说,Swift提供了熟悉的语法和API风格,但同时也引入了诸如类型推断、可选类型和枚举等高级特性,使得代码更加简洁明了。Swift的现代化语法允许开发者编写更高效、更易于维护的代码,同时保持与现有Cocoa和Cocoa Touch框架的兼容性。
Swift的设计目标是重新定义软件开发的方式,它鼓励开发者以一种更直观、更直观的方式来表达意图,减少冗余代码和潜在的错误。此外,Swift还引入了交互式开发环境,使得代码的调试和迭代更为迅速。Swift的出现标志着Apple在移动应用开发语言上的又一次重大突破,预示着未来的iOS和OS X应用将更加高效、稳定且具有更高的用户体验。
Swift不仅是对Objective-C的进化,更是Apple对其开发者工具和技术栈的一次革新,它以简洁、安全和现代的形式,推动了iOS和OS X平台应用开发的新篇章。随着Swift的普及,越来越多的开发者将享受到它所带来的高效开发环境和卓越性能,进一步推动了整个苹果生态系统的发展。
Type Aliases
Type aliases
define an alternative name for an existing type. You define type aliases with the typealias keyword.
Type aliases are useful when you want to refer to an existing type by a name that is contextually more appropriate, such as when working with data of a specific size from an external source:
typealias AudioSample = UInt16
Once you define a type alias, you can use the alias anywhere you might use the original name:
1 v ar maxAmplitudeFound = AudioSample.min
2 // maxAmplitudeFound is now 0
Here, AudioSample is defined as an alias for UInt16. Because it is an alias, the call to AudioSample.min actually calls UInt16.min, which provides an initial value of 0 for the maxAmplitudeFound variable.
Booleans
Swift has a basic
Boolean
type, called Bool. Boolean values are referred to as
logical
, because they can only ever be true or false. Swift provides two Boolean constant values, true and false:
1 let orangesAreOrange = true
2 let turnipsAreDelicious = false
The types of orangesAreO range and turnipsAreDelicious have been inferred as Bool from the fact that they were initialized with Boolean literal values. As with Int and Double above, you don’t need to declare constants or variables as Bool if you set
them to true or false as soon as you create them. Type inference helps make Swift code more concise and readable when it initializes constants or variables with other values whose type is already known.
Boolean values are particularly useful when you work with conditional statements such as the if statement:
1 if turnipsAreDelicious {
2 println("Mmm, tasty turnips!")
3 } else {
4 println("Eww, turnips are horrible.")
5 }
6 // prints "Eww, turnips are horrible."
Conditional statements such as the if statement are covered in more detail in Control Flow.
Swift’s type safety prevents non-Boolean values from being be substituted for Bool. The following example reports a compile-time error:
1 let i = 1
2 if i {
3 // this example will not compile, and will report an error
4 }
However, the alternative example below is valid:
1 let i = 1
2 if i == 1 {
3 // this example will compile successfully
4 }
The result of the i == 1 comparison is of type Bool, and so this second example passes the type-check. Comparisons like i == 1 are discussed in Basic Operators.
As with other examples of type safety in Swift, this approach avoids accidental errors and ensures that the intention of a particular section of code is always clear.
Tuples
Tuples
group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.
In this example, (404, "Not Found") is a tuple that describes an
HTTP status code
. An HTTP status code is a special value returned by a web server whenever you request a web page. A status code of 404 Not Found is returned if you request a
webpage that doesn’t exist.
1 let http404Error = (404, "Not Found")
2 // http404Error is of type (Int, String), and equals (404, "Not Found")
The (404, "Not Found") tuple groups together an Int and a String to give the HTTP status code two separate values: a number and a human-readable description. It can be described as “a tuple of type (Int, String)”.
You can create tuples from any permutation of types, and they can contain as many different types as you like. There’s nothing stopping you from having a tuple of type (Int, Int, Int), or (String, Bool), or indeed any other permutation you require.
You can
decompose
a tuple’s contents into separate constants or variables, which you then access as usual:
1 let (statusCode, statusMessage) = http404Error
2 println("The status code is \(statusCode)")
3 // prints "The status code is 404"
4 println("The status message is \(statusMessage)")
5 // prints "The status message is Not Found"
If you only need some of the tuple’s values, ignore parts of the tuple with an underscore (_) when you decompose the tuple:
1 let (justTheStatusCode, _) = http404Error
2 println("The status code is \(justTheStatusCode)")
3 // prints "The status code is 404"
Alternatively, access the individual element values in a tuple using index numbers starting at zero:
1 println("The status code is \(http404Error.0)")
2 // prints "The status code is 404"
3 println("The status message is \(http404Error.1)")
4 // prints "The status message is Not Found"
You can name the individual elements in a tuple when the tuple is defined:
let http200Status = (statusCode: 200, description: "O K")
If you name the elements in a tuple, you can use the element names to access the values of those elements:
1 println("The status code is \(http200Status.statusCode)")
2 // prints "The status code is 200"
3 println("The status message is \(http200Status.description)")
4 // prints "The status message is OK"
Tuples are particularly useful as the return values of functions. A function that tries to retrieve a web page might return the (Int, String) tuple type to describe the success or failure of the page retrieval. By returning a tuple with two distinct values,
each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type. For more information, see Functions with Multiple Return Values.
N O T E
Tuples are useful for temporary groups of related v alues. They are not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a
tuple. For more information, see Classes and Structures.
Optionals
You use
optionals
in situations where a value may be absent. An optional says:
or
N O T E
The concept of optionals doesn’t exist in C or O bjective-C. The nearest thing in O bjective-C is the ability to return nil from a method that would otherwise return an object, with nil meaning “the absence of a valid object.” However, this only
works for objects—it doesn’t work for structs, basic C types, or enumeration v alues. For these types, Objective-C methods typically return a special value (such as NSNotF ound) to indicate the absence of a value. This approach assumes that
the method’s caller knows there is a special value to test against and remembers to check for it. Swift’s optionals let you indicate the absence of a value for
any type at all
, without the need for special constants.
Here’s an example. Swift’s String type has a method called toInt, which tries to convert a String value into an Int value. However, not every string can be converted into an integer. The string "123" can be converted into the numeric value 123, but the
string "hello, world" does not have an obvious numeric value to convert to.
The example below uses the toInt method to try to convert a String into an Int:
1 let possibleNumber = "123"
2 let convertedNumber = possibleNumber.toInt()
3 // convertedNumber is inferred to be of type "Int?", or "optional Int"
Because the toInt method might fail, it returns an
optional
Int, rather than an Int. An optional Int is written as Int?, not Int. The question mark indicates that the value it contains is optional, meaning that it might contain
some
Int value, or it might
contain
no value at all
. (It can’t contain anything else, such as a Bool value or a String value. It’s either an Int, or it’s nothing at all.)
If Statements and Forced Unwrapping
You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to true; if it has no value at all, it evaluates to false.
Once you’re sure that the optional
does
contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value;
please use it.” This is known as
forced unwrapping
of the optional’s value:
1 if conv ertedNumber {
2 println("\(possibleNumber) has an integer value of \(conv ertedNumber!)")
3 } else {
4 println("\(possibleNumber) could not be conv erted to an integer")
5 }
6 // prints "123 has an integer v alue of 123"
For more on the if statement, see Control Flow.
N O T E
Trying to use ! to access a non-existent optional value triggers a runtime error. Alway s make sure that an optional contains a non-nil value before using ! to force-unwrap its value.
Opt ional Binding
You use
optional binding
to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if and while statements to check for a value inside an optional,
and to extract that value into a constant or variable, as part of a single action. if and while statements are described in more detail in Control Flow.
Write optional bindings for the if statement as follows:
if let constantName = someOptional {
statements
}
You can rewrite the possibleNumber example from above to use optional binding rather than forced unwrapping:
1 if let actualNumber = possibleNumber.toInt() {
2 println("\(possibleNumber) has an integer value of \(actualNumber)")
3 } else {
4 println("\(possibleNumber) could not be conv erted to an integer")
5 }
6 // prints "123 has an integer v alue of 123"
This can be read as:
“If the optional Int returned by possibleNumber.toInt contains a value, set a new constant called actualNumber to the value contained in the optional.”
There
is
a value, and it equals
x
•
There
isn’t
a value at all•
If the conversion is successful, the actualNumber constant becomes available for use within the first branch of the if statement. It has already been initialized with the value contained
within
the optional, and so there is no need to use the ! suffix to
access its value. In this example, actualNumber is simply used to print the result of the conversion.
You can use both constants and variables with optional binding. If you wanted to manipulate the value of actualNumber within the first branch of the if statement, you could write if var actualNumber instead, and the value contained within the optional
would be made available as a variable rather than a constant.
nil
You set an optional variable to a valueless state by assigning it the special value nil:
1 v ar serv erResponseCode: Int? = 404
2 // serverResponseCode contains an actual Int value of 404
3 serv erResponseCode = nil
4 // serverResponseCode now contains no v alue
N O T E
nil cannot be used with non-optional constants and v ariables. If a constant or v ariable in your code needs to be able to cope with the absence of a value under certain conditions, alway s declare it as an optional value of the appropriate type.
If you define an optional constant or variable without providing a default value, the constant or variable is automatically set to nil for you:
1 v ar surv eyA nswer: String?
2 // surveyA nswer is automatically set to nil
N O T E
Swift’s nil is not the same as nil in Objective-C . In O bjective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of
any
type can be set to nil, not just object types.
Implicitly Unwrapped Opt ionals
As described above, optionals indicate that a constant or variable is allowed to have “no value”. Optionals can be checked with an if statement to see if a value exists, and can be conditionally unwrapped with optional binding to access the optional’s
value if it does exist.
Sometimes it is clear from a program’s structure that an optional will
always
have a value, after that value is first set. In these cases, it is useful to remove the need to check and unwrap the optional’s value every time it is accessed, because it can be
safely assumed to have a value all of the time.
These kinds of optionals are defined as
implicitly unwrapped optionals
. You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.
Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in
Swift is during class initialization, as described in Unowned References and Implicitly Unwrapped Optional Properties.
An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a nonoptional value, without the need to unwrap the optional value each time it is accessed. The following example shows the difference in behavior
between an optional String and an implicitly unwrapped optional String:
1 let possibleString: String? = "An optional string."
2 println(possibleString!) // requires an exclamation mark to access its value
3 // prints "An optional string."
4
5 let assumedString: String! = "An implicitly unwrapped optional string."
6 println(assumedString) // no exclamation mark is needed to access its value
7 // prints "An implicitly unwrapped optional string."
You can think of an implicitly unwrapped optional as giving permission for the optional to be unwrapped automatically whenever it is used. Rather than placing an exclamation mark after the optional’s name each time you use it, you place an
exclamation mark after the optional’s type when you declare it.
N O T E
If you try to access an implicitly unwrapped optional when it does not contain a value, you will trigger a runtime error. The result is exactly the same as if you place an exclamation mark after a normal optional that does not contain a value.
You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value:
1 if assumedString {
2 println(assumedString)
3 }
4 // prints "An implicitly unwrapped optional string."
You can also use an implicitly unwrapped optional with optional binding, to check and unwrap its value in a single statement:
1 if let definiteString = assumedString {
2 println(definiteString)
3 }
4 // prints "An implicitly unwrapped optional string."
N O T E
Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.
Assertions
Optionals enable you to check for values that may or may not exist, and to write code that copes gracefully with the absence of a value. In some cases, however, it is simply not possible for your code to continue execution if a value does not exist,
or if a provided value does not satisfy certain conditions. In these situations, you can trigger an
assertion
in your code to end code execution and to provide an opportunity to debug the cause of the absent or invalid value.
Debugging with A ssertions
An assertion is a runtime check that a logical condition definitely evaluates to true. Literally put, an assertion “asserts” that a condition is true. You use an assertion to make sure that an essential condition is satisfied before executing any further
code. If the condition evaluates to true, code execution continues as usual; if the condition evaluates to false, code execution ends, and your app is terminated.
If your code triggers an assertion while running in a debug environment, such as when you build and run an app in Xcode, you can see exactly where the invalid state occurred and query the state of your app at the time that the assertion was
triggered. An assertion also lets you provide a suitable debug message as to the nature of the assert.
You write an assertion by calling the global assert function. You pass the assert function an expression that evaluates to true or false and a message that should be displayed if the result of the condition is false:
1 let age = -3
2 assert(age >= 0, "A person's age cannot be less than zero")
3 // this causes the assertion to trigger, because age is not >= 0
In this example, code execution will continue only if age >= 0 evaluates to true, that is, if the value of age is non-negative. If the value of age
is
negative, as in the code above, then age >= 0 evaluates to false, and the assertion is triggered,
terminating the application.
Assertion messages cannot use string interpolation. The assertion message can be omitted if desired, as in the following example:
assert(age >= 0)
When t o Use A ssertions
Use an assertion whenever a condition has the potential to be false, but must
definitely
be true in order for your code to continue execution. Suitable scenarios for an assertion check include:
See also Subscripts and Functions.
N O T E
Assertions cause your app to terminate and are not a substitute for designing y our code in such a way that inv alid conditions are unlikely to arise. Nonetheless, in situations where inv alid conditions are possible, an assertion is an effective way
to ensure that such conditions are highlighted and noticed during development, before y our app is published.
An integer subscript index is passed to a custom subscript implementation, but the subscript index value could be too low or too high.•
A value is passed to a function, but an invalid value means that the function cannot fulfill its task.•
An optional value is currently nil, but a non-nil value is essential for subsequent code to execute successfully.•
Basic Operators
An
operator
is a special symbol or phrase that you use to check, change, or combine values. For example, the addition operator (+) adds two numbers together (as in let i = 1 + 2). More complex examples include the logical AND operator && (as in if
enteredDoorC ode && passedRetinaScan) and the increment operator ++i, which is a shortcut to increase the value of i by 1.
Swift supports most standard C operators and improves several capabilities to eliminate common coding errors. The assignment operator (=) does not return a value, to prevent it from being mistakenly used when the equal to operator (==) is
intended. Arithmetic operators (+, -, *, /, % and so forth) detect and disallow value overflow, to avoid unexpected results when working with numbers that become larger or smaller than the allowed value range of the type that stores them. You can
opt in to value overflow behavior by using Swift’s overflow operators, as described in Overflow Operators.
Unlike C, Swift lets you perform remainder (%) calculations on floating-point numbers. Swift also provides two range operators (a..b and a...b) not found in C, as a shortcut for expressing a range of values.
This chapter describes the common operators in Swift. Advanced Operators covers Swift’s advanced operators, and describes how to define your own custom operators and implement the standard operators for your own custom types.
Terminology
Operators are unary, binary, or ternary:
The values that operators affect are
operands
. In the expression 1 + 2, the + symbol is a binary operator and its two operands are the values 1 and 2.
Assignment Operator
The
assignment operator
(a = b) initializes or updates the value of a with the value of b:
1 let b = 10
2 v ar a = 5
3 a = b
4 // a is now equal to 10
If the right side of the assignment is a tuple with multiple values, its elements can be decomposed into multiple constants or variables at once:
1 let (x, y) = (1, 2)
2 // x is equal to 1, and y is equal to 2
Unlike the assignment operator in C and Objective-C, the assignment operator in Swift does not itself return a value. The following statement is not valid:
1 if x = y {
2 // this is not valid, because x = y does not return a value
3 }
This feature prevents the assignment operator (=) from being used by accident when the equal to operator (==) is actually intended. By making if x = y invalid, Swift helps you to avoid these kinds of errors in your code.
Arithmetic Operators
Swift supports the four standard
arithmetic operators
for all number types:
1 1 + 2 // equals 3
2 5 - 3 // equals 2
3 2 * 3 // equals 6
4 10.0 / 2.5 // equals 4.0
Unlike the arithmetic operators in C and Objective-C, the Swift arithmetic operators do not allow values to overflow by default. You can opt in to value overflow behavior by using Swift’s overflow operators (such as a &+ b). See Overflow Operators.
The addition operator is also supported for String concatenation:
"hello, " + "world" // equals "hello, world"
Two Character values, or one Character value and one String value, can be added together to make a new String value:
1 let dog: Character = ""
2 let cow: Character = ""
3 let dogCow = dog + cow
4 // dogCow is equal to ""
See also Concatenating Strings and Characters.
Remainder Operator
The
remainder operator
(a % b) works out how many multiples of b will fit inside a and returns the value that is left over (known as the
remainder
).
N O T E
The remainder operator (% ) is also known as a
modulo operator
in other languages. However, its behavior in Swift for negative numbers means that it is, strictly speaking, a remainder rather than a modulo operation.
Here’s how the remainder operator works. To calculate 9 % 4, you first work out how many 4s will fit inside 9:
Unary
operators operate on a single target (such as -a). Unary
prefix
operators appear immediately before their target (such as !b), and unary
postfix
operators appear immediately after their target (such as i++).•
Binary
operators operate on two targets (such as 2 + 3) and are
infix
because they appear in between their two targets.•
Ternary
operators operate on three targets. Like C, Swift has only one ternary operator, the ternary conditional operator (a ? b : c).•
Addition (+)•
Subtraction (-)•
Multiplication (*)•
Division (/)•
剩余168页未读,继续阅读
2018-12-20 上传
2021-10-05 上传
2021-10-05 上传
2019-07-11 上传
2019-08-15 上传
2020-05-27 上传
2021-11-05 上传
「已注销」
- 粉丝: 0
- 资源: 2
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 新代数控API接口实现CNC数据采集技术解析
- Java版Window任务管理器的设计与实现
- 响应式网页模板及前端源码合集:HTML、CSS、JS与H5
- 可爱贪吃蛇动画特效的Canvas实现教程
- 微信小程序婚礼邀请函教程
- SOCR UCLA WebGis修改:整合世界银行数据
- BUPT计网课程设计:实现具有中继转发功能的DNS服务器
- C# Winform记事本工具开发教程与功能介绍
- 移动端自适应H5网页模板与前端源码包
- Logadm日志管理工具:创建与删除日志条目的详细指南
- 双日记微信小程序开源项目-百度地图集成
- ThreeJS天空盒素材集锦 35+ 优质效果
- 百度地图Java源码深度解析:GoogleDapper中文翻译与应用
- Linux系统调查工具:BashScripts脚本集合
- Kubernetes v1.20 完整二进制安装指南与脚本
- 百度地图开发java源码-KSYMediaPlayerKit_Android库更新与使用说明
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功