翻译进度
13
分块数量
5
参与人数

我喜欢 Swift 的十个优点
2

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。

file

在经过了两个多月沉浸在 Swift 语言中并且捣鼓了一些 iOS 开发内容后,我想整理一下我的一些想法,关于为什么我开始完全享受用 Swift 工作并且提供一些资源来阐述我是如何快速的从完全小白到充满自信的用 Swift 构建 iOS 应用程序。

我有全栈开发的背景,但这也就意味着我不能在任何一个计算机科学领域中被称为专家 : ) 。但是,我在 Python , Scala 和 Javascript 等其它语言都做过专业的工作,所以我的观点可能会因为我过去在这些语言领域的工作经验而不同。

注意:我在使用 Swift 3 ,Xcode 8 和 iOS 10

PJHubs 翻译于 9个月前

1. 可读性

Programs must be written for people to read, and only incidentally for machines to execute. --- Harold Abelson

程序编写时必须以易读性为目标,机器可执行性只是附加条件而已。 —— Harold Abelson

这是我在作为一名软件工程师生涯中努力遵守的原则。到目前为止,我觉得 Swift 表达能力强且易于使用,同时给未来的我(或其它人)维持了可读性。这让我有了认为一门“现代”编程语言应该是什么样的感觉,它有倾向于简化和按照你所期望的语法,作为 Objective-C 的进化,消去了多余的符号和沉重的语法。

这里有一些简单的字符串格式化拼接怎么在 Objective-C,Swift 和 Python 中实现的例子:

// Objective-C
NSString *name = @"Nate";
NSString *str = [NSString stringWithFormat:@"Hello %@, how are you today?", name];
// Swift
let name = "Nate"
let str = "Hello \(name), how are you today?"
// Python
name = "Nate"
str = "Hello %s, how are you today?" % name

有几个我不得不适应的 Swift 安全规则,并且我每天都在学习,但是 Swift 总体上是一个用通俗的语言来读写代码。

获得一些关于 Swift 中级语法的文章, 请查看本文

PJHubs 翻译于 8个月前

2. 函数式编程

Swift 不是纯粹的函数式编程语言,但坚决地接受高阶函数,例如 mapfilterreduce 和 flatMap

这里有一个例子,可以作为函数式编程如何简化代码的简明概要:

// 数组中的每个数字加 5,然后返回偶数结果
let numbers = [1, 2, 3, 4, 5]
// 传统的、命令式的方法
var newNumbers: [Int] = []
for number in numbers {
    let newNum = number + 5
    if newNum % 2 == 0 {
        newNumbers.append(newNum)
    }
}
// 函数式、声明式的方法
var newNumbersFP = numbers.map { $0 + 5 }.filter { $0 % 2 == 0 }

你可以争论命令式方法更具可读性,尤其是在函数式的功能链和代码复杂性失控时。但是对于特定的使用场景,请将这些高阶函数视为你的工具带中的一个额外的工具。

高阶函数可能非常的强大,因此想深入了解,详见 这篇文章

iDev_01 翻译于 9个月前

3. 类型安全

Swift 引入了可选类型,它能安全的处理异常值。它逼迫我们明确的处理 nil 情况,以保证我们不会对变量的含义编写出任何糟糕的代码。

举个例子,当一个变量为字符串可选类型时,我们知道是该变量是字符串或没有值其中之一。Swift 提供了一些方式给我们安全的处理该情况(可称为安全解包):

  • guard:
guard let str = strOptional else {
    return
}
// str 目前安全的被解包并且保证从这里拿到的是字符串类型
  • if let:
if let str = strOptional {
   print("This is a string: \(str)")
}
  • optional chaining:
class Person {
    var pet: Pet?  // ? 意思为 pet 是一个 Pet 可选类型
}
class Pet {
    var numberOfPets: Int = 3
}
let me = Person()
let numberOfPets = me.pet?.numberOfPets
// numberOfPets 是一个 Int 可选类型并且如果 pet 是 nil 时将会安全的赋为 nil
// 或者使用 “if let” 来安全解包:
if let petCount = me.pet?.numberOfPets {
    print("Pet count is \(petCount)")
}
  • nil 和条件合并:
let numberOfPets = me.pet?.numberOfPets ?? 0
let hasPets = numberOfPets > 0 ? true : false
// 这还能被写得更短:let hasPets = numberOfPets > 0

还有很多地方可以表现出 Swift 的类型安全,并且使用这些方法可以有很多种思路去组织代码使其更加安全和易读。开始的时候可能会令人沮丧,因为 Swift 会督促检查处理可选值(但不是强迫你进行安全化.....可参考 forced unwrapping),很难编写出不合规的代码。但请记住,Xcode 是你的朋友并且当你使用可选类型时它将于你合作。

Xcode 是你的朋友!

在一天结束时,Swift 的安全构建已经印在了我的脑海中,预先阻止了很多不同类型的问题和运行时错误。这可能意味着这门语言是十分严谨的,但从长远来看语言开发者们希望合适和明确的类型处理能够节省时间。

PJHubs 翻译于 8个月前

4. 面向协议编程

我承认,从开始到现在花了很多时间才能理解它。这有 protocol-oriented programming (面向协议编程), structs and value type semanticsdon't repeat yourself (DRY 原则) 并且还有臭名昭著的 infamous Crusty talk ,所以在早期这些主题内容把我给喂饱了,并且一直影响我。

但事情开始变得明了是因为我开始全身心投入并开始使用多个协议和协议拓展重构我的代码。在使用协议(蓝图)实现并遵守我众多的类和结构体,定义协议拓展(默认的方法实现)的过程中,我开始看见可重用的例子和模块代码,并且关注把我的胖视图控制器缩减为更可控的大小。这带来了一个很大的副作用是我更倾向于组合而不是继承,所以我不能让我通过父类或继承不必要属性和方法把对象变得臃肿。

我没有利用这点来为面向协议编程伸张正义。似乎有无尽的利用 Swift 协议和值类型的用例,并且我深知自己只是触及到了表面。如果你有任何于面向协议编程的例子值得分享欢迎进行讨论!

除了上边所示的链接,这还有一些我找到有助于我继续沉迷于其中的资源:

PJHubs 翻译于 8个月前

5. 属性观察器

这是我最喜欢的 Swift 开箱即用功能之一。 通过一个例子来理解它会非常简单:

var score = 0 {
    willSet {
        print("Score is about to change to \(newValue)")
    }
    didSet {
        print("Score just changed from \(oldValue) to \(score)")
    }
}
score = 50
// Score is about to change to 50
// Score just changed from 0 to 50

我最喜欢的属性观察器使用场景之一是更新表视图:

var toDoListTasks: [Task] = [] {
    didSet {
        DispatchQueue.main.async {
            self.tasksTableView.reloadData()
        }
    }
}
toDoListTasks.append(Task("clean kitchen"))
// 表视图会自动刷新

来自苹果官方文档的说明:

当变量或属性被初始赋值的时候,属性观察器 [willSet, didSet] 并不会被调用。相反,只有在初始化上下文之外赋值时属性观察器才会发挥作用。

SankerXR 翻译于 8个月前

6. 类型推断

Swift 编译器能够推断常量或变量的类型,这可以使你的代码保持简短清晰。

var number = 5              // 不需要使用 var number: Int = 5 来显式标明类型
let pi = 3.14159            // pi 会被推断为 Double 类型
let stillPi = 3 + 0.14159   // 没错, 仍然是 Double 类型
view.backgroundColor = .yellow   // 不需要使用 UIColor.yellow
SankerXR 翻译于 8个月前

7. 自定义函数参数标签

Swift 另一个小巧的特性: 在函数中自定义或者省略参数标签以便代码更容易阅读。

func moveBox(_ box: Box, from start: Point, to end: Point) {
    // 移动箱子!
}
let aBox = Box()
moveBox(aBox, from: Point(0,0), to: Point(5,5))

Xcode 能够帮助你在调用函数的时候非常轻松地补全参数。

不止一次地你会发现,Xcode 真是人类的好朋友啊!

SankerXR 翻译于 8个月前

8. Swift Playground

Since Swift's initial release in 2014, playgrounds in Xcode have been around, allowing developers to quickly experiment with live code in an interactive environment, instead of having to continually go through a compile-run-test cycle.

Coming from a Python environment, I would have felt empty inside if this wasn't possible with Swift, but I think playgrounds are to be appreciated for a compiled language! Swift playgrounds aren't perfect and can get bogged down and slow to use in Xcode, but it's still been super helpful as I've ramped-up and experimented with Swift code.

I haven't yet used playgrounds for UI mockups, but I can only imagine how powerful and lightweight it must feel for those used to developing for iOS in Objective-C without the ability to quickly experiment.

9. Open-source

Want to know how Strings or Collections or anything else in the Swift standard library works? Or how about even lower-level implementation details of the Swift language? Well now you can! Swift has been open-sourced since Swift 2.2, and the Swift Evolution project continues to provide transparency with what's coming in future releases of Swift.

Chris Lattner (founder of Swift) and team knew from day one that Swift would eventually be open-sourced, so kept full commit history all the way back to their very first commit. If you notice in those files, the copyright text says "Copyright © 2014--2015 Apple Inc.", whereas the checkin was made in 2010! So it could be that 1) the team rewrote git history for some reason, 2) this was intentional to remind them that Apple wanted them to deliver in 2014--2015, or 3) Chris Lattner is a sorcerer.

10. Swift documentation

Apple's Swift documentation reads like a book. They explain things in simple-to-understand English while laying out great examples, and I oftentimes find answers to my questions directly from their docs (as opposed to Stack Overflow), which I cannot say about other languages I've worked in.

I've learned about how closures and automatic reference counting work directly from the Swift docs, and even began my Swift journey on their Jump Right In page by building out a simple table view app. They've done a really great job with these docs and I'd highly recommend going directly to them before heading to Stack Overflow when working through your next problem.

11. Community

Ok I couldn't leave this one out, so it's going to be 11 things I like about Swift.

The Swift community has been more than welcoming as I've learned the ins-and-outs of iOS development, working in Xcode and ramped-up on Swift.

First, I love how there have been standards put forth from the wild that seem to have mass adoption, like Ray Wenderlich's Swift style guide and the super customizable SwiftLint project from Realm for enforcing those standards, driven by the community. It's given me comfort in knowing that there's a well established way of doing things that much of the community agrees with, allowing me to focus on the important stuff.

Second, the active, online community of people who have willingly lended a helping hand as I worked through problems and had iOS/Swift related questions. Over my last couple months, I've leaned on the iOS developers Slack group, iOS developers on Twitter and countless websites and bloggers dedicated to teaching newbie iOS developers like myself.

Finally, those who built and contributed to the open-source project that is Swift. They've clearly built something that people love (4th most loved language!) and we shouldn't take for granted all the work that has paved the way to what Swift is today.

Before you go...

You might be saying to yourself... this dude can't possibly have nothing bad to say about Swift?! You're right, there are certainly things that come to mind that have frustrated me about working in the language. To name just a few: lack of modules/namespacing (although there are tricks), JSON serialization using just Swift Core Libraries was a pain (I'm now using SwiftyJSON) and String manipulation and various String operations were brutal to work with (for good reason; but there seem to be a lot of improvements coming in Swift 4).

I opted to stick with the positives, as my overall experience with Swift has been beyond positive. I have so much more to learn (and be frustrated with), so figured that topic can wait.

Lastly, here's a list of places I'd recommend for those just starting to learn Swift and iOS development that really helped me:

You can reach me on Twitter @nathanwchan, or leave a comment below. I'll also be attending 360iDev in Denver this month (August 2017) to continue my Swift and iOS journey, so if you're going to be there, don't be a stranger!

本文章首发在 iOS 技术社区
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://medium.com/ios-os-x-development/...

译文地址:https://ioscaff.com/topics/174/i-like-th...

参与译者:5
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

  • 请注意单词拼写,以及中英文排版,参考此页
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`, 更多语法请见这里 Markdown 语法
  • 支持表情,使用方法请见 Emoji 自动补全来咯,可用的 Emoji 请见 :metal: :point_right: Emoji 列表 :star: :sparkles:
  • 上传图片, 支持拖拽和剪切板黏贴上传, 格式限制 - jpg, png, gif
  • 发布框支持本地存储功能,会在内容变更时保存,「提交」按钮点击时清空
  请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!