قالب وردپرس درنا توس
Home / IOS Development / Swift Tips: Wrapper Features

Swift Tips: Wrapper Features



For this year's update to Advanced Swift, we add the possibility of a video clip (just like we did for App Architecture). One of the videos in the bundle shows how we pack Cairo, a vector graphics drawing library.

In our wrapper we must do the following:

  let the surface = try SVGSurface (size: CGSize (width: 800, height: 600))
let context = try context (surface)
context.drawSomething ()
surface.finish ()
print (surface.data)

Before we access the data in the context, we should call surface.finish () . And after we call surface.finish () we really shouldn't draw with context anymore. Instead of putting this into the documentation, we can also provide another API that prevents us from making this error:

  func svg (size: CGSize, _ draw: (Context) -> ()) cast -> Data {
let the surface = try SVGSurface (size: size)
let context = try context (surface)
draw (context)
surface.finish ()
return the surface data
}

Now that we want to create an SVG, we call the function with our drawing code:

  let data = try svg (CGSize (width: 800, height: 600)) {context in
context.drawSomething ()
}

In the example above, we cannot access the surface directly, and we cannot forget to call finish () ̵

1; this is handled by the cover.

We can use The same technique in many places. For example, in Core Graphics (which looks like Cairo), there is an API that stores the graphics status of a CGContext and another that recovers it. Calls to these APIs should be balanced. Instead of calling them directly, we can again write a wrapping function that balances the calls for us:

  CGContext extension {
func withLocalGraphicsState (_ draw: () -> ()) {
saveGState ()
draw()
restoreGState ()
}
}

You can use similar APIs when working with resources that need balanced calls: Open and close a file, lock and unlock a shared resource, or push and pop any state. We use this pattern through our projects. It is much nicer to move these possible points of error out of our domain-specific code and to help code that we can test and verify once.

The video tape will be launched briefly, along with the new edition of Advanced Swift. If you already own the ebook, the release update will be free. The videos will be optional, as a paid upgrade. See our Twitter for an announcement!




Source link