笔者认为学习swift最好从swift官网开始,于是就开始了这样一段旅程:
文章目录
Swift
The powerful programming language that is also easy to learn.
翻译:强大的编程语言,也很容易学习。
Swift is a powerful and intuitive programming language for macOS, iOS, watchOS, tvOS and beyond. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love. Swift code is safe by design, yet also produces software that runs lightning-fast.
翻译:Swift是一种适用于macOS、iOS、watchOS、tvOS等平台的强大而直观的编程语言。编写Swift代码具有交互性和趣味性,语法简洁而富有表现力,Swift还包含了开发人员喜爱的现代功能。Swift code在设计上是安全的,但其软件运行速度也像闪电一样快。
Modern(现代)
Swift is the result of the latest research on programming languages, combined with decades of experience building Apple platforms. Named parameters are expressed in a clean syntax that makes APIs in Swift even easier to read and maintain. Even better, you don’t even need to type semi-colons. Inferred types make code cleaner and less prone to mistakes, while modules eliminate headers and provide namespaces. To best support international languages and emoji, Strings are Unicode-correct and use a UTF-8 based encoding to optimize performance for a wide-variety of use cases. Memory is managed automatically using tight, deterministic reference counting, keeping memory usage to a minimum without the overhead of garbage collection.
翻译:Swift是对编程语言最新研究的成果,加上数十年构建苹果平台的经验。命名参数用干净的语法表示,这使得Swift中的api更容易读取和维护。更好的是,您甚至不需要输入分号。推断类型使代码更简洁,更不容易出错,而模块消除了标题并提供了名称空间。为了最好地支持国际语言和表情符号,字符串是unicode正确的,并使用基于UTF-8的编码来优化各种用例的性能。使用严格的、确定性的引用计数自动管理内存,在没有垃圾收集开销的情况下将内存使用保持在最低限度。
struct Player {
var name: String
var highScore: Int = 0
var history: [Int] = []
init(_ name: String) {
self.name = name
}
}
var player = Player("Tomas")
Declare new types with modern, straightforward syntax. Provide default values for instance properties and define custom initializers.
翻译:使用现代、直观的语法声明新类型。为实例属性提供默认值并定义自定义初始化器。
extension Player {
mutating func updateScore(_ newScore: Int) {
history.append(newScore)
if highScore < newScore {
print("\(newScore)! A new high score for \(name)! 🎉")
highScore = newScore
}
}
}
player.updateScore(50)
// Prints "50! A new high score for Tomas! 🎉"
// player.highScore == 50
Add functionality to existing types using extensions, and cut down on boilerplate with custom string interpolations.
翻译:使用扩展向现有类型添加功能,使用自定义字符串插值减少样板文件。
extension Player: Codable, Equatable {}
import Foundation
let encoder = JSONEncoder()
try encoder.encode(player)
print(player)
// Prints "Tomas, games played: 1, high score: 50”
Quickly extend your custom types to take advantage of powerful language features, such as automatic JSON encoding and decoding.
翻译:快速扩展您的自定义类型,以利用强大的语言特性,例如自动JSON编码和解码。
let players = getPlayers()
// Sort players, with best high scores first
let ranked = players.sorted(by: { player1, player2 in
player1.highScore > player2.highScore
})
// Create an array with only the players’ names
let rankedNames = ranked.map { $0.name }
// ["Erin", "Rosana", "Tomas"]
Perform powerful custom transformations using streamlined closures.
翻译:使用streamlined闭包执行强大的自定义转换。
These forward-thinking concepts result in a language that is fun and easy to use.
Swift has many other features to make your code more expressive:
- Generics that are powerful and simple to use
- Protocol extensions that make writing generic code even easier
- First class functions and a lightweight closure syntax
- Fast and concise iteration over a range or collection
- Tuples and multiple return values
- Structs that support methods, extensions, and protocols
- Enums can have payloads and support pattern matching
- Functional programming patterns, e.g., map and filter
- Native error handling using try / catch / throw
翻译:这些前瞻性的概念造就了一种有趣且易于使用的语言。
Swift有许多其他功能,使您的代码更富有表现力: - 功能强大、使用简单的泛型
- 协议扩展,使编写通用代码更容易
- 一流的函数和轻量级闭包语法
- 快速和简洁的迭代范围或集合
- 元组和多个返回值
- 支持方法、扩展和协议的结构体
- 枚举可以有有效载荷和支持模式匹配
- 函数式编程模式,如map和filter
- 使用try / catch / throw的本地错误处理
Designed for Safety(为安全设计)
Swift eliminates entire classes of unsafe code. Variables are always initialized before use, arrays and integers are checked for overflow, memory is automatically managed, and enforcement of exclusive access to memory guards against many programming mistakes. Syntax is tuned to make it easy to define your intent — for example, simple three-character keywords define a variable ( var ) or constant ( let ). And Swift heavily leverages value types, especially for commonly used types like Arrays and Dictionaries. This means that when you make a copy of something with that type, you know it won’t be modified elsewhere.
Another safety feature is that by default Swift objects can never be nil. In fact, the Swift compiler will stop you from trying to make or use a nil object with a compile-time error. This makes writing code much cleaner and safer, and prevents a huge category of runtime crashes in your apps. However, there are cases where nil is valid and appropriate. For these situations Swift has an innovative feature known as optionals. An optional may contain nil, but Swift syntax forces you to safely deal with it using the ? syntax to indicate to the compiler you understand the behavior and will handle it safely.
翻译:
Swift消除了不安全代码的整个类。变量在使用前总是被初始化,数组和整数被检查是否溢出,内存被自动管理,并且强制执行对内存的独占访问可以防止许多编程错误。语法被调优以使定义您的意图变得容易—例如,简单的三个字符的关键字定义了一个变量(var)或常量(let)。而且Swift很大程度上利用了值类型,特别是常用的类型,如数组和字典。这意味着,当您使用该类型复制某个内容时,您知道它不会在其他地方被修改。
另一个安全特性是默认情况下Swift对象不可能为nil。事实上,Swift编译器会阻止你试图制造或使用nil对象的编译时错误。这使得编写代码更加干净和安全,并防止了应用程序中大量的运行时崩溃。然而,在有些情况下nil是有效的和适当的。对于这些情况,Swift有一个创新的功能,称为选项。一个可选的可能包含nil,但Swift语法强制您使用?语法,以指示编译器您理解该行为并将安全地处理它。
extension Collection where Element == Player {
// Returns the highest score of all the players,
// or `nil` if the collection is empty.
func highestScoringPlayer() -> Player? {
return self.max(by: { $0.highScore < $1.highScore })
}
}
Use optionals when you might have an instance to return from a function, or you might not.
翻译:当您可能有实例要从函数返回,或者没有实例时,请使用选项。
if let bestPlayer = players.highestScoringPlayer() {
recordHolder = """
The record holder is \(bestPlayer.name),\
with a high score of \(bestPlayer.highScore)!
"""
} else {
recordHolder = "No games have been played yet.")
}
print(recordHolder)
// The record holder is Erin, with a high score of 271!
let highestScore = players.highestScoringPlayer()?.highScore ?? 0
// highestScore == 271
翻译:
可选绑定、可选链接和nil合并等特性使您可以安全地、高效地使用可选值。
Fast and Powerful(快速和强大的)
From its earliest conception, Swift was built to be fast. Using the incredibly high-performance LLVM compiler technology, Swift code is transformed into optimized native code that gets the most out of modern hardware. The syntax and standard library have also been tuned to make the most obvious way to write your code also perform the best whether it runs in the watch on your wrist or across a cluster of servers.
Swift is a successor to both the C and Objective-C languages. It includes low-level primitives such as types, flow control, and operators. It also provides object-oriented features such as classes, protocols, and generics, giving Cocoa and Cocoa Touch developers the performance and power they demand.
翻译:
从它最早的概念开始,Swift就被设计成快速的。使用令人难以置信的高性能LLVM编译技术,Swift代码被转换为优化的本地代码,充分利用现代硬件。语法和标准库也进行了调优,使最明显的编写代码的方式也能发挥最佳性能,无论它是运行在您的手腕上的手表上还是运行在服务器集群上。
Swift是C语言和Objective-C语言的继承者。它包括低级原语,如类型、流控制和操作符。它还提供了面向对象的特性,如类、协议和泛型,为Cocoa和Cocoa Touch开发人员提供了他们所需要的性能和能力。
Great First Language(伟大的第一语言)
Swift can open doors to the world of coding. In fact, it was designed to be anyone’s first programming language, whether you’re still in school or exploring new career paths. For educators, Apple created free curriculum to teach Swift both in and out of the classroom. First-time coders can download Swift Playgrounds—an app for iPad that makes getting started with Swift code interactive and fun.
翻译:
Swift可以打开通往编码世界的大门。事实上,它被设计成任何人的第一种编程语言,无论你是在上学还是在探索新的职业道路。对于教育工作者来说,苹果创造了免费课程在教室内外教授斯威夫特。第一次编写代码的人可以下载Swift playground,这是一款iPad应用程序,可以让你在开始编写Swift code时既互动又有趣。
Aspiring app developers can access free courses to learn to build their first apps in Xcode. And Apple Stores around the world host Today at Apple Coding & Apps sessions where you can get hands-on experience with Swift code.
翻译:有抱负的应用程序开发人员可以访问免费课程,学习如何用Xcode构建他们的第一个应用程序。世界各地的苹果商店今天举办了苹果编码和应用程序会议,在那里你可以获得Swift代码的实际经验。
Source and Binary Compatibility(源代码和二进制兼容性)
With Swift 5, you don’t have to modify any of your Swift 4 code to use the new version of the compiler. Instead you can start using the new compiler and migrate at your own pace, taking advantage of new Swift 5 features, one module at a time. And Swift 5 now introduces binary compatibility for apps. That means you no longer need to include Swift libraries in apps that target current and future OS releases, because the Swift libraries will be included in every OS release going forward. Your apps will leverage the latest version of the library in the OS, and your code will continue to run without recompiling. This not only makes developing your app simpler, it also reduces the size of your app and its launch time.
翻译:源代码和二进制兼容性
在Swift 5中,你不需要修改任何Swift 4代码来使用新版本的编译器。相反,您可以开始使用新的编译器,并按照自己的节奏迁移,利用新的Swift 5特性,一次一个模块。Swift 5现在引入了应用程序的二进制兼容性。这意味着你不再需要在针对当前和未来OS版本的应用中包含Swift库,因为在未来的每个OS版本中都会包含Swift库。您的应用程序将利用操作系统中库的最新版本,您的代码将继续运行而无需重新编译。这不仅简化了应用程序的开发,还减少了应用程序的大小和启动时间。
Open Source
Swift is developed in the open at Swift.org, with source code, a bug tracker, forums, and regular development builds available for everyone. This broad community of developers, both inside Apple as well as hundreds of outside contributors, work together to make Swift even more amazing. There is an even broader range of blogs, podcasts, conferences and meetups where developers in the community share their experiences of how to realize Swift’s great potential.
翻译:
Swift是在Swift.org上公开开发的,每个人都可以使用它的源代码、bug跟踪器、论坛和常规开发版本。这个广泛的开发者社区,包括苹果内部的开发者和数百名外部贡献者,共同努力使Swift变得更加出色。还有更广泛的博客、播客、会议和聚会,社区的开发者可以在这里分享他们如何实现Swift巨大潜力的经验。
Cross Platform(跨平台的)
Swift already supports all Apple platforms and Linux, with community members actively working to port to even more platforms. With SourceKit-LSP, the community is also working to integrate Swift support into a wide-variety of developer tools. We’re excited to see more ways in which Swift makes software safer and faster, while also making programming more fun.
翻译:
Swift已经支持所有的苹果平台和Linux,社区成员正积极致力于移植到更多的平台。通过使用SourceKit-LSP,社区还致力于将Swift支持集成到各种各样的开发工具中。我们很高兴看到Swift能以更多的方式让软件更安全、更快,同时也让编程更有趣。
Swift for Server()
While Swift powers many new apps on Apple platforms, it’s also being used for a new class of modern server applications. Swift is perfect for use in server apps that need runtime safety, compiled performance and a small memory footprint. To steer the direction of Swift for developing and deploying server applications, the community formed the Swift Server work group. The first product of this effort was SwiftNIO, a cross-platform asynchronous event-driven network application framework for high performance protocol servers and clients. It serves as the foundation for building additional server-oriented tools and technologies, including logging, metrics and database drivers which are all in active development.
To learn more about the open source Swift community and the Swift Server work group, visit Swift.org
翻译:
虽然Swift为苹果平台上的许多新应用程序提供了强大的支持,但它也被用于一种新的现代服务器应用程序。Swift是完美的用于服务器应用,需要运行时安全,编译性能和一个小内存占用。为了引导Swift开发和部署服务器应用程序的方向,社区成立了Swift服务器工作组。这项工作的第一个产品是SwiftNIO,这是一个跨平台异步事件驱动的网络应用框架,用于高性能协议服务器和客户端。它是构建其他面向服务器的工具和技术的基础,包括日志、指标和数据库驱动程序,这些都在积极开发中。
要了解更多关于Swift开源社区和Swift服务器工作组的信息,请访问Swift
Playgrounds and Read-Eval-Print-Loop (REPL)
Much like Swift Playgrounds for iPad, playgrounds in Xcode make writing Swift code incredibly simple and fun. Type a line of code and the result appears immediately. You can then Quick Look the result from the side of your code, or pin that result directly below. The result view can display graphics, lists of results, or graphs of a value over time. You can open the Timeline Assistant to watch a complex view evolve and animate, great for experimenting with new UI code, or to play an animated SpriteKit scene as you code it. When you’ve perfected your code in the playground, simply move that code into your project. Swift is also interactive when you use it in Terminal or within Xcode’s LLDB debugging console. Use Swift syntax to evaluate and interact with your running app, or write new code to see how it works in a script-like environment.
翻译:
就像iPad上的Swift Playgrounds一样,Xcode中的Playgrounds让编写Swift代码变得非常简单和有趣。键入一行代码,结果立即出现。然后,您可以从代码的侧面快速查看结果,或者直接将结果钉在下面。结果视图可以显示图形、结果列表或随时间变化的值图形。您可以打开时间轴助手来观察复杂视图的演变和动画,这对于试验新的UI代码非常好,或者在您编写代码时播放一个动画SpriteKit场景。当你在操场上完善你的代码时,只需将代码移到你的项目中。当您在终端或在Xcode的LLDB调试控制台使用Swift时,它也是交互式的。使用Swift语法评估运行中的应用程序并与之交互,或者编写新代码以了解它在类似脚本的环境中是如何工作的。
Package Manager(包管理器)
Swift Package Manager is a single cross-platform tool for building, running, testing and packaging your Swift libraries and executables. Swift packages are the best way to distribute libraries and source code to the Swift community. Configuration of packages is written in Swift itself, making it easy to configure targets, declare products and manage package dependencies. New to Swift 5, the swift run command now includes the ability to import libraries in a REPL without needing to build an executable. Swift Package Manager itself is actually built with Swift and included in the Swift open source project as a package.
翻译:
Swift软件包管理器是一个用于构建、运行、测试和打包Swift库和可执行文件的跨平台工具。Swift软件包是向Swift社区分发库和源代码的最佳方式。包的配置是用Swift本身编写的,这使得配置目标、声明产品和管理包依赖关系变得很容易。Swift 5新增的Swift run命令现在可以在REPL中导入库,而不需要构建可执行文件。实际上,Swift包管理器本身是用Swift构建的,并作为一个包包含在Swift开源项目中。
Objective-C Interoperability(objective - c的互操作性)
You can create an entirely new application with Swift today, or begin using Swift code to implement new features and functionality in your app. Swift code co-exists along side your existing Objective-C files in the same project, with full access to your Objective-C API, making it easy to adopt.
翻译:
您现在可以使用Swift创建一个全新的应用程序,或者开始使用Swift代码在您的应用程序中实现新的特性和功能。Swift代码与您现有的Objective-C文件共存于同一个项目中,可以完全访问您的Objective-C API,使其易于采用。
Get Started(开始)
Download Xcode and learn how to build apps using Swift with documentation and sample code.
翻译:
下载Xcode,学习如何使用Swift创建应用程序,并提供文档和示例代码。
View resources>