Skip to Content
Swift游戏开发经典实例
book

Swift游戏开发经典实例

by Jonathon Manning, Paris Buttfield-Addison
January 2020
Intermediate to advanced
356 pages
6h 4m
Chinese
China Electric Power Press Ltd.
Content preview from Swift游戏开发经典实例
30
1
讨论
在编写需要长时间运行的任务时,我们经常需要使用这种以闭包作为参数的方法定
义。有时候,我们想在某个任务结束时执行某些代码,同时还想让这些代码在调用
时临时指定,那么也经常采用这种方式。
闭包是
Swift
语言新加入的特性。在此之前,我们通常需要写两个方法来实现同样
的目的:一个方法用于执行需要长时间运行的耗时任务;另一个方法用于在第一个
方法完成时回调。这种方式将代码完全分割成了两个独立的部分,减少了代码的可
读性。而且,在两个方法间,变量的传递变得复杂(因为这需要使用到临时变量,
先将值保存到这些临时变量中,然后又从这些临时变量中取出值,而使用闭包则根
本不用管这些)。
如果调用方法时,传递给该方法的最后一个参数是一个闭包,则我们可以将
闭包放在方法调用的圆括号之外(这是使用了尾末闭包的写法。当闭包是方
法参数中最后一个参数时,这个参数可以移到方法调用之外,即的右圆括号
之后)。这是出于增加可读性的目的。
1.13
使用
Operation Queues
问题
我们可以将一些工作放入队列,以便操作系统在
CPU
有空时执行这些任务。
解决方案
OperationQueue
用于调度闭包,将之放到后台执行,而不会阻塞如渲染图形或接
受用户输入等实时任务的执行:
//
创建一个任务队列,用于调度多个任务
let concurrentQueue = OperationQueue()
//
设置该队列可同时执行的任务数为
10
concurrentQueue.maxConcurrentOperationCount = ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

精通機器學習

精通機器學習

Aurélien Géron
FreeBSD® Unleashed

FreeBSD® Unleashed

Brian Tiemann, Michael C. Urban
深入淺出代數

深入淺出代數

Tracey Pilone, Dan Pilone
Swift学习手册

Swift学习手册

Jon Manning, Paris Buttfield-Addison, Tim Nugent

Publisher Resources

ISBN: 9787519840129