The Low-Level Frameworks

Most of the frameworks described thus far work with fairly high-level abstractions: locations, sprites, workouts, movies, and so on. These frameworks are implemented atop lower-level frameworks and libraries that sometimes offer additional features, but are generally more primitive and harder to code for.

For example, AV Foundation is built atop Core Audio, Core Video, and Core Media, all C-based APIs for working with buffers of audio or frames of video. There are things you can do at this level that are not exposed at the AV Foundation level, but it is usually more difficult: you are responsible for handling more things (like memory management and type safety), there are more ways the code can crash, and there is usually less documentation and sample code.

Furthermore, most of these lower-level APIs are meant to be called from C-language code. In almost all cases, it’s technically possible to call them from Swift, but it is not particularly pleasant. Many of the C APIs cannot provide the kind of type safety that Swift enforces, so instead of having a function that takes a meaningful type like an AVPlayerItem for a podcast file or a movie, they’ll take an UnsafeMutablePointer. That’s all Swift can do to represent a C pointer that otherwise has no concept of type, and it’s not kidding about the “unsafe” part; the number-one cause of crashing C apps is screwing up pointers, and bringing them into your Swift code doesn’t make them any safer.

In Xcode’s documentation viewer, most of these frameworks are listed under the System section, and our advice for the beginning programmer is to just stay away. For the intermediate and advanced developer, our experience has been that calling non-Swift APIs from Swift is more trouble than it’s worth—the resulting code is not only hard to follow for Swift developers, it’s less readable than its C equivalent. Instead, just write these parts in C or C++. An Xcode project can combine source files of different types, so if you have a lot of Metal or Core Audio code, just write all of that idiomatically in C/C++, and then expose a small number of Swift methods or functions to call into your C code from your Swift app.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset