Wednesday, June 29, 2016

A U.S. analogy of the Brexit situation

Confused about the "Brexit" situation? Here's how it might go down if the United States were actually the United Kingdom.




The Tea Party hates being part of the European Union because they have to pay a bunch of money, the EU gets to make some laws that affect the US, and immigrants can come in from anywhere in the EU with very few restrictions. They've been complaining about it for years. Finally, Prime Minister Paul Ryan agrees to schedule a non-binding national vote on whether they should leave, figuring it will fail and the Tea Party will have to stop talking about it.

So Sarah Palin goes about campaigning on how terrible the EU is, and how all the money we send to the EU could go toward education instead! $350 million every week to education! Wouldn't that be awesome? And by the way, look at all these immigrants coming in and making it harder for you to get jobs. Isn't that terrible? "Take Back Control" is their slogan.

Paul Ryan recognizes that leaving would be a terrible blow to the economy, so he's encouraging everyone to Remain. The Republican party leadership runs campaigns like "Brits Don't Quit" and stuff, which are fine and all, but it's not as inspiring or scaremongery as "Take Back Control", so the Leave campaign is picking up quite a bit of steam.

This is a national vote, not just a Republican vote, so the Democrats need to be involved too. They're in favor of staying, generally… except that it turns out Nancy Pelosi (the leader of the Democrats in our little story) privately actually has never liked the EU all that much, and would kinda be okay with leaving. So she puts some token effort into supporting the Remain campaign, but doesn't put much effort into it.

Paul Ryan recognizes that they're going to need the Democrat vote on the Remain side if they're going to win. The general leadership of both parties is on the Remain side, so it seems like the one time that they might actually agree on something! But… no. Nancy Pelosi flat out refuses to be seen cooperating with Paul Ryan. Democrats are getting mixed messages. Polls are predicting a narrow win for Remain, but it's a close thing.

The week before the vote, a Democrat senator from Pennsylvania named Jo Cox is shot and killed outside a library where she was about to hold a town hall meeting. She was a supporter of the Remain movement. The shooter was known to be affiliated with far-right extremist groups, and Cox's "Remain" stance and her support for immigration is suspected as a motive for the shooting.

The day of the vote comes, and in a 52%-48% split, Leave wins. Soon, there are reports of Leave supporters harassing and assaulting foreigners across Britain, telling them to get out of the country where "they are not wanted".

Paul Ryan says that he won't be the one to lead the US out of the EU, and announces his upcoming resignation. In the meantime, he's in no hurry to formally notify the EU of any departure. Reporters ask him "what's the plan for exiting the EU?" and he says "Not my problem."

Sarah Palin didn't actually expect the Leave campaign to win; she was mostly looking to score political points. Now the rubber hits the road, and she has to admit that immigration is still going to happen and there's *definitely* not $350 million actually available to go toward education. Leave voters are *super* upset with her. The Dollar starts falling dramatically in value. Sarah Palin announces that after this long and tiring campaign, she's going to take a month off from public appearances, and generally doesn't want to admit that she has no idea how an exit from the EU would actually work.

Democrats are furious with Nancy Pelosi over her weak support of the Remain movement. They produce a 172-40 vote of no confidence in her leadership, and much of the other party leadership resigns too. Pelosi vows to stay in power since the no confidence vote is non-binding, but everyone assumes she'll be gone before long, and there's a lot of questions over who will replace her.

Texas voted heavily in favor of Remain. The governer of Texas says that if the US is going to leave the EU, maybe Texas will secede from the Union and join the EU on its own.

Rumors start spreading that many people were confused about what the vote actually meant (even though the ballot was pretty dang clear), and soon there are millions of signatures on a petition for a re-vote.


So at this point:

  • The leader of the Republicans (Paul Ryan) has stepped down.
  • His presumptive replacement (Sarah Palin) is in hiding.
  • The leader of the Democrats (Nancy Pelosi) is likely to be ousted.
  • Texas is threatening to secede.
  • Nobody wants to actually be the one to notify the EU of the US departure, as it's probably political suicide.
  • Nobody's sure whether the US is staying or leaving, but everyone's unhappy with the situation.


Got it?

Starring: 

Paul Ryan as David Cameron
Sarah Palin as Boris Johnson
Nancy Pelosi as Jeremy Corbyn
Tea Party as UKIP
"$350m to Education" as "£350m to the NHS"
Texas as Scotland



Thanks for reading. If I've messed something up, please let me know!

Tuesday, June 7, 2016

Swift Protocols constrained to a specific class

Objective-C developers learning Swift often wonder how to represent something like UIViewController<MyProtocol>. The simple answer is that there's currently no way to directly represent that construct in Swift as of Swift 2.2. However, it's possible to work around it fairly easily with just a tiny bit of extra code.

protocol KitchenHelper: class {
    // The normal protocol stuff here
    func bakeCookies()
    func eatCake()

    // The new stuff
    var asViewController: UIViewController { get }
}

We've added an additional constraint to the protocol; any object that implements KitchenHelper must be able to return a UIViewController as well. Presumably, any conforming view controller would want to simply return self, so lets make that easier:

extension KitchenHelper where Self: UIViewController {
    // Let's provide a default implementation for view controllers
    var asViewController: UIViewController { return self }
}

Now any view controller class that conforms to KitchenHelper will automatically implement asViewController as well!

class MyViewController: UIViewController, KitchenHelper {
    func bakeCookies() {
        // sugar, flour, eggs...
    }

    func eatCake() {
        // yum
    }

    // 'asViewController' was automatically implemented!
}

func test() {
    let helper: KitchenHelper = MyViewController()
    let frame = helper.asViewController.view.frame
    print("helper's view's frame:", frame)
}

Sunday, June 14, 2015

Thoughts on WWDC 2015

In my mind, these are biggest developer-facing announcements to come out of WWDC 2015:
  • iPad Multitasking
  • UI Testing and Code Coverage in Xcode 7
  • Swift 2
  • Swift as an Open-Source language
  • App Thinning
  • Watch OS 2.0 with on-device apps
  • CloudKit Web Services
  • Free iOS provisioning
Note that these aren't changes in the SDK itself. Developers don't have to write a lot of code to get these benefits. iPad multitasking already works if you followed the adaptivity guidance for iOS 8 from last year; support is as simple as recompiling. UI Testing works on your existing apps. On-watch WatchKit extensions use the same SDK that on-phone extensions used (albeit with additional capabilities exposed). You don't need to make any changes to your CloudKit usage in order to enable web services. All these features come essentially free for the developer.

There are, of course, some nice SDK changes as well. UIStackView and NSCollectionView are very welcome additions to their respective platforms, but even these aren't really new; they're just parity features between the platforms. The various new extension points are nice, and the new gaming frameworks are probably a big deal for game developers. But as I see it, WWDC doesn't fundamentally change the kinds of apps I can write.

The focus this year isn't on enabling new kinds of apps, but rather on improving the experience of the apps we can already build. App testing, delivery, performance, and consumption are all improved across the board, with little effort needed from developers. iOS 9 and OS X El Capitan offer significant improvements to the user experience, and Xcode 7 improves the developer experience, but the improvements are largely outside the SDK. The big news from WWDC 2015 isn't about new frameworks, classes, and methods—it's about an improved experience for users and developers.



Caveat: If you're a game developer, GameplayKit, ReplayKit, and the expanded Metal announcements may have made this a big year for you. I'm not a game developer, so they don't really affect me from a development standpoint. But I acknowledge that they definitely look cool, and are definitely part of the SDK.

Saturday, May 2, 2015

Defining Modules for Static Libraries

Preview:

I figured out how to define modules for static libraries, so you can import them into Swift or into other module-defining frameworks. This solves a common build error: "include of non-modular header inside framework module", as it allows you to turn that non-modular header into a modular one.

You just have to define a custom module.modulemap file and copy it into the right place. Read more for details, or skip to the end if you just want to know what to do.




A brief and incomplete rationale for modules

In 2013, Xcode 5 was released with support for modules, a new way of using libraries and frameworks. Xcode 5 only supported modules in system libraries, but Xcode 6 extended support to third-party libraries as well. Before the advent of modules, developers gained access to libraries via #import statements, which literally copy the requested header files into the importing file. This made the library APIs visible within that file, but required repeatedly parsing system headers again and again as multiple files imported the same headers. This is an unnecessary duplication of work.

We could greatly improve build times if the compiler could parse all the headers of a library just once. However, this is difficult in a #import-based system, because the compiler does not know what files constitute the canonical headers for any given library. Some libraries provide an "umbrella" header that imports all of its API, but the compiler can't always know what header that would be, and even these aren't always complete. (Example: UIKit.h does not import UIGestureRecognizerSubclass.h.) We needed a better way of defining the canonical interface for a given library.

Modules are that better way. A module is a binary representation of a library's interface—once built, the module can be reused throughout the entire compilation process. It can also be used to provide access to the library from other languages, such as Swift. In fact, Swift code can only make use of frameworks and libraries that have a module defined, so this becomes a critical piece of infrastructure going forward.

Module maps

So how do we define a module from a bunch of headers? How do we define the canonical API for a library? Module maps. A module map is a simple file that defines the canonical headers for a library. They're easiest to understand by example, so let's jump right in.

The following is a valid module map for an imaginary library. It is place in a file named module.modulemap in the same directory as the library headers.

module AirplaneKit {
   header "Airplane.h"
   header "AirplaneView.h"
   header "Cockpit.h"
   header "Fuselage.h"
   header "Wheels.h"
   header "Wings.h"
}

Simple enough; the module map is just a list of headers that define the representation of the library. It can get a bit tedious to write out every header, though, and it's easy to forget to update the modulemap when you add a new header, so module maps support a convenient syntax:

module AirplaneKit {
   umbrella header "AirplaneKit.h"
   export *
}

That export * line means "Also consider any file imported by one of the listed headers to be part of the module." This is generally what you'll want to do. (The umbrella part is not strictly necessary, but indicates that the header is expected to import every header file in its directory.)

In general, Xcode has fairly good support for defining modules based on your own frameworks: just set the Defines Module build setting to YES and maintain your framework's umbrella header. Xcode will build the appropriate module map file and embed it within your framework. Support for static libraries, though, is somewhat lacking.

Before we move on, one important note: In Xcode 6.3.1, you must clean your project after any change to a module.modulemap file. In my experience, the compiled version of the module is not rebuilt when the module map file changes. Also, when tweaking the module map file, make sure you're editing your original file, not the one in the build folder. Xcode sometimes likes to jump to that one instead.

Defining modules for static libraries

If you're using a static library and you want to make it available to Swift or to another module, there are 2 things you need to do to "modularize" it.

1. Add a file named exactly module.modulemap as described above.

2a. If you're using someone else's library you didn't write, you probably already put the headers somewhere. Just write a module map file for the library and put it with the headers.

2b. If you're building your own static library, make sure your library's headers and the module map are being copied to [build directory]/include/[LibraryName]/. If your static library target is using a Copy Headers build step (as is the default in Xcode 6.3.1), remove it. Instead add a Copy Files build phase, configured as follows:



That's it. Really. After doing the above, you can now use your library from Swift. You can read more about modules and the modulemap format in the Clang Documentation.

If you have any problems, please let me know on Twitter (@bjhomer). I'd like to make sure these steps work for everyone.

Saturday, October 18, 2014

Mutable collections in Swift

I recently came across this question on Twitter:


This is an interesting question. As a developer coming from Objective-C and the Cocoa frameworks, we're used to distinguishing between NSArray and NSMutableArray. It's generally bad practice to expose an NSMutableArray as a public property on an object.


The problem is that another part of the app could modify the contents of the pizzaMenu array without the knowledge of the Pizzeria object. The Pizzeria still points to the same object it always has; from its perspective, nothing has changed. This is bad.


Instead, a better practice is to only expose an immutable NSArray. This way, whenever any change happens, the setter method will be called. The Pizzeria is always aware of what's happening.

In Swift, the Array type is built into the language. Though you can still use NSArray and NSMutableArray, it's often not necessary; the native Array type is plenty capable.

There are two types of objects in Swift: value types and reference types. Reference types are like traditional Objective-C objects—multiple variables can reference the same object. This was the problem in the examples above above: both the Pizzeria object and external code referenced the same object, so we had to expose an NSArray that does not have APIs for changing its contents.

Value types are identified by their value. They also exist in Objective-C, but only for C types (structs and primitives). If two CGRect variables have the same value, it simply means that the two rects contain the same data. A change to one rect will never change the value of another rect stored in a separate variable.

While Objective-C requires that all objects be reference types, Swift objects can be reference or value types. This means that Swift structs can have methods just like classes can. Swift's built-in collections (Array and Dictionary) are value types.

Because they are value types, two variables can never reference the "same" array. Every time an array is assigned to a variable, it gets a new, separate copy1 which cannot be affected by any other part of the code.

This means there is no need for a separate mutable collection type in Swift. Mutating a value type is always safe because changing a struct only affects the values of that specific variable. That what it means to be a value type. Modifying a Swift Array never affects any other variable, anywhere.

Let's see how this affects our pizzeria example.

Note that even though pizzeria.pizzaMenu is a mutable var property, modifying the array we get back from the pizzeria has no effect on the pizzeria's copy of the data. They are separate arrays, separate values, and we can't change their copy unless we go through the setter.

In fact, this holds true even if we avoid assigning the array to an intermediate variable! In Objective-C, you simply cannot modify a value type held by another object. Many iOS developers have discovered this, to their frustration:

But in Swift, not only does this work, but it guarantees that the setter will be called! Whenever you call a mutating2 method on a value type, the end result is assigned back into the receiving variable (or expression). So calling obj.someInts.append(1) causes a new value to be constructed, which is then assigned back into the someInts property!


Because Swift arrays and dictionaries can never be shared, there is no distinction between mutating an existing collection and re-assigning a new collection. The behavior of the code is exactly the same. In either case, the owner's setter method is called whenever the array is modified.

So to answer the original question, there is no syntax to specify a variable that holds an immutable array because there is nothing that such syntax would add. Swift addresses the issues that made NSArray and NSMutableArray necessary in the first place. If you need a shared array, you can still use the Cocoa types. In every other case, Swift's solution is safer, simpler, and more concise.



1: Note that the implementation is lazy, only performing an actual copy when really necessary.
2: Methods on structs and enums in Swift must be labeled mutating if they're going to modify any data. Otherwise, they cannot be called on a value stored in a let variable.

Friday, August 8, 2014

NSScrollView and Autolayout

So, you've got an NSScrollView, and you want to add some content that is sized via auto layout constraints. Perhaps you found the "Auto Layout by Example" documentation in the Mac developer library, and discovered that though it contains a section titled Using Scroll Views with Auto Layout, the example is actually for UIScrollView, not NSScrollView. Given the significant differences between the two, that simply won't work.

Here's what you need to do. I'll demonstrate doing this in code, but the same principles apply in Interface Builder as well.



1. Create an NSScrollView. Position it however you like.

    _scrollView = [[NSScrollView alloc] initWithFrame:self.bounds];
    _scrollView.translatesAutoresizingMaskIntoConstraints = YES;
    _scrollView.autoresizingMask = NSViewHeightSizable | NSViewWidthSizable;
    _scrollView.hasVerticalScroller = YES;
    _scrollView.identifier = @"ScrollView";

    [self addSubview:_scrollView];


2. Create an NSView subclass with isFlipped == YES that will contain all your scrolling content.  (If it's not flipped, then the content will prefer to pin to the bottom of the scroll view if not tall enough to require scrolling. That's not what you want.)

    @interface FlippedView : NSView
    @end

    @implementation FlippedView

    - (BOOL)isFlipped {
        return YES;
    }

    @end

3. Create the scrolling container view. Do not use autoresizing masks. Its size doesn't matter too much, but its superview will be the scroll view's contentView, so that makes a convenient default size.

    _scrollContentContainer = [[FlippedView alloc]
                                initWithFrame:_scrollView.contentView.bounds];
    _scrollContentContainer.translatesAutoresizingMaskIntoConstraints = NO;
    _scrollContentContainer.identifier = @"Content container";

4. Set the content container to be the scroll view's document view.

    _scrollView.documentView = _scrollContentContainer;

5. Constrain the top, left, and right edges of the container view to its superview (the contentView). Use Auto Layout constraints to do this, not autoresizing masks.

    NSDictionary *views = NSDictionaryOfVariableBindings(_scrollContentContainer);
    NSArray *hConstraints = [NSLayoutConstraint
                             constraintsWithVisualFormat:@"H:|[_scrollContentContainer]|"
                             options:0 metrics:nil views:views];
    
    NSArray *vConstraints = [NSLayoutConstraint
                             constraintsWithVisualFormat:@"V:|[_scrollContentContainer]"
                             options:0 metrics:nil views:views];
    [_scrollView.contentView addConstraints:hConstraints];
    [_scrollView.contentView addConstraints:vConstraints];
    
6. Add your subviews to the content container however you like. Make sure that the constraints from these subviews will create a natural content size in at least the vertical dimension.

    NSDictionary *buttons = NSDictionaryOfVariableBindings(button, button2);
    NSArray *hConstraints2 = [NSLayoutConstraint
                              constraintsWithVisualFormat:@"V:|-[button]-(1300)-[button2]-|"
                              options: (NSLayoutFormatAlignAllLeft |
                                        NSLayoutFormatAlignAllRight)
                              metrics:nil views:buttons];
    
    NSLayoutConstraint *centerX = [NSLayoutConstraint
                                   constraintWithItem: button
                                   attribute: NSLayoutAttributeCenterX
                                   relatedBy: NSLayoutRelationEqual
                                   toItem:    _scrollContentContainer
                                   attribute: NSLayoutAttributeCenterX
                                   multiplier:1 constant:0];
    
    [_scrollContentContainer addConstraints:hConstraints2];
    [_scrollContentContainer addConstraint:centerX];


Of course, you can do this all in Interface Builder as well, and that's usually what I'd do. It's nice to know how to do it both ways, though. The same principles apply in either case:

  1. Position the NSScrollView externally however you like.
  2. Flipped container view as the scroll view's document view.
  3. Constraints from top, right, and left of container view to its superview.
  4. Constraints from the scrollable content to the container view.

And that's it!

Tuesday, August 5, 2014

Mormon Questions: Temples

A couple weeks ago, my brother was married in the temple in Bountiful, Utah. Temples are an important part of my beliefs as a member of the Church of Jesus Christ of Latter-Day Saints, so I thought I'd take some time to explain what they're about and answer some common questions.

First, though, a brief note. To understand our temples, you must understand that our religion is not just a codified series of moral guidelines. We believe that God is a real, physical being who communicates with us and blesses us as we follow his teachings. We also believe that each of us has a spirit which continues to live on after our death. The temple binds us to God eternally, far beyond our brief time here on Earth. If you try to understand the temple while ignoring these things, the things we do in the temple will make very little sense.

Bountiful, Utah temple. Click to see more photos.

Outside the temple

If you know anything about Mormon temples, you probably know that they've got beautiful architecture. Temples usually have stained glass windows, intricate stonework, and a design that draws the eye heavenward. Each temple is built to be a house of the Lord, a place where God is welcome. Quite literally, the phrase "The House of the Lord" is inscribed on the exterior of every temple. We make every effort to make each temple a beautiful place, representative of the respect and love we have for God.

"Holiness to the Lord. The House of the Lord."
Temple in Madrid, Spain

The grounds of each temple are generally open to the public and show the same dedication to serenity and peacefulness. They usually feature gardens and fountains, shade trees and benches, and it's common to see people taking pictures on the grounds or sitting on a bench study scriptures. Many temples also have visitor's centers, where guests can get more information and ask questions.

Fountain at the Oakland, California temple

Inside the temple

Temples are sacred buildings where we participate in ordinances (religious rituals or ceremonies) and make covenants with God. They are set apart from the outside world, dedicated to a specific purpose and free from external distractions. Upon entering, attendees change into white clothing and leave behind cell phones and other distractions. The temple is a quiet, peaceful, and reverent place. We are asked to speak in a whisper if we speak at all. Some rooms are set aside simply for contemplation and prayer, while others are meant to accommodate a specific ordinance.

If you've visited the churches or cathedrals of other religions, you might expect the interior of the temple to be a vast open space. In fact, the interior of each temple is simply a series of rooms, each with its own purpose. There are ceremonial rooms, administrative offices, hallways, chapels, and small meeting rooms, but no massive space for congregating. The same care that goes into the exterior of the temple goes into the interior as well; there are crystal chandeliers, intricate carvings and designs, beautiful stairways, etc. You can find some pictures of the interior of the temple on lds.org. (I was unable to find good photos of the temple interior that were licensed for use on other websites, so I'm afraid you'll just have to follow the link on this one.)

Temples are distinct from our meetinghouses, where regular Sunday worship takes place. In meetinghouses, we gather each week to learn about Christ through scripture study, talks, hymns, etc. We also take the sacrament (often known as "communion" in other Christian religions.) None of this happens in temples; in fact, our temples are not even open on Sundays. Temples are specifically focused on sacred ceremonies, not worship services. (If you're interested in attending one of our Sunday meetings, you can find a nearby meetinghouse on mormon.org.)

Temple ordinances (ceremonies)

That's my brother and sister-in-law. They're awesome.
The most celebrated ordinance held in the temple is eternal marriage. Mormons believe that a marriage under proper authority in the temple is effective not only "until death do you part," but throughout eternity. Mormons are known for a strong emphasis on the family, and this is part of the reason why—we believe that family life is not just a transient phase while we're here on earth, but rather an essential part of our eternal future. In the temple, couples are "sealed together" for time and all eternity, creating a new family unit that will last forever.

Another ceremony held in the temple is known as the endowment. It includes instruction about the pre-mortal existence of man, the creation of the world, the story of Adam and Eve in the Garden of Eden, and their path back to God's presence. As with many scriptural accounts, the lessons to be learned from the endowment are not necessarily the literal ones in the text. Just as Christ wasn't teaching us that we should all literally build our houses upon rocks, the endowment isn't really instruction about how to live in the Garden of Eden. It's symbolic, a metaphor for our own lives. During the endowment, we make covenants (promises) to follow the teachings of Jesus Christ and to participate in his Church.

After we have received ordinances for ourselves, we can also go to the temple to receive ordinances for the dead. This may seem unfamiliar, but it's a beautiful concept. Religious ordinances (baptism, endowment, marriage, etc.) enable us to live with God again and to receive tremendous opportunities and blessings. Without these ordinances, we cannot ever receive all that God wants to give us. However, there are many, many people who have died without ever having the opportunity to participate in these ordinances. It might seem that millions upon millions of God's children are condemned by no fault of their own.

Baptistry in the Salt Lake City temple

But God cares about all of his children. We believe that those who never had an adequate chance to learn about Jesus Christ and his teachings in this life will have that opportunity in the next life, being taught by those who have previously learned it. But learning is not enough; ordinances such as baptism are required for our eternal progression, and it's rather difficult to baptize a spirit. So, after we (the living) have received these ordinances for ourselves, we can go to temples as a proxy for those who have died, and participate in various ordinances on their behalf. We are especially urged to do this work for our own ancestors, offering them the same opportunities that we have received. Baptisms for the dead, endowments for the dead, and even marriages for the dead are all performed in the temple in order to extend the blessings of each ordinance to those who have gone before.

It would be incorrect, though, to say "Well, we've done a baptism for Gertrude Hazelswatch (born in 1628), so now she's a Mormon too." When we participate in temple ceremonies on behalf of the dead, we are only offering up the physical part of the ordinance. Each deceased person continues to live on as a spirit, and the baptism we perform on their behalf means nothing unless that person accepts the associated commitments. If they do not accept the commitments associated with baptism, they are not bound by them and the baptism means nothing. However, we cannot know who will accept or reject these commitments, so we offer them to as many as we can and hope that they will accept it.

Visiting the temple

In order to preserve the reverent atmosphere that exists in temples, dedicated temples are only open to church members in good standing. However, after construction on a temple is completed, a temple "open house" event is held over several weeks. During this time, the public is invited to tour the temple. These open houses are usually very well attended, as it is the only chance for the general public to enter the temple. There are only a few temples built each year worldwide, so these open houses are fairly rare. If you happen to be in Utah this month, it might be worth your time to visit the Ogden, Utah temple open house, roughly 45 minutes north of Salt Lake City. The temple has been undergoing major renovations, and will be dedicated in September 2014. Reservations to attend are available free online.

There's also a temple nearing dedication in Phoenix, Arizona. Open House dates have not yet been announced, but it will probably be late 2014.

If you're not going to be able to catch an open house, you might be interested in stopping by a visitor's center. There are 143 temples in operation around the world, including many throughout North America, and most temples have visitor's centers that are open 7 days a week. You can find a list of temples here.

And that's it! If you've got a question I didn't answer or if you just want to tell me what you think, feel free to ask me on Twitter (@bjhomer) or send me an email (bjhomer@gmail.com).