swiftnscodingdecodernscoder

What do the words before variables mean in init()s?


Sorry for terrible question, but I've been reading the swift book and following tutorials, and I've found about this NSCoder protocol and disabling it and whatnot.

required init(coder aDecoder: NSCoder) {
    fatalError("not been implemented")
}

I understand about required inits, but I don't understand this code I have to write. Does it say that if a NSCoder is passed, a fatal error occurs? Also, what does the word coder mean? Why do I need it there in front of the variable name?


Solution

  • The purpose of that code is to fulfill the requirement of the NSCoding protocol, which says that you must implement init(coder:), without actually bothering to write any meaningful implementation of that method. If you had something meaningful to do here, you would delete the fatalError line and do something meaningful. As it is, you are saying: "I have no implementation for this, so if it ever is called, we are in serious trouble and I want to crash deliberately!"

    The word coder is an "external name" for this parameter. In Swift, parameters can have both an internal name and an external name. coder means, when you call this function, call this parameter coder: (which in fact is just what you do). It is absolutely necessary because this is how the world, including Cocoa, sees this function; coder: is part of its name, its identity. However, the word aDecoder is just the internal name of the local parameter, and is merely a serving suggestion; you can use another internal name or you could even delete it, which would make the internal name the same as the external name.

    The situation here is that you are overriding a Cocoa function, and you must use the correct name of that function. That means the function name, the external parameter names, and the parameter types. They must all be exactly right, or it won't be the same function as the function you are supposed to be overriding. But the internal parameter names, the local variables passed into the body of the function, are up to you, and you can change them if you like. I often do.