Swift Tips: Declarations


Use final on properties and methods when you know that a declaration does not need to be overridden. This allows the compiler to replace these dynamically dispatched calls with direct calls. You can even mark an entire class as final by attaching the attribute to the class itself.

When properties do not need to be overridden

class Blogpost {
	final var title: String?
	final var subTitle: String? 
	final var post: String?
}

When the whole class does not need to be overridden

final class Blogpost {
	var title: String?
	var subTitle: String? 
	var post: String?
}

Straight from Apple Documentation
Preventing Overrides You can prevent a method, property, or subscript from being overridden by marking it as final. Do this by writing the final modifier before the method, property, or subscript’s introducer keyword (such as final var, final func, final class func, and final subscript).

Any attempt to override a final method, property, or subscript in a subclass is reported as a compile-time error. Methods, properties, or subscripts that you add to a class in an extension can also be marked as final within the extension’s definition.

You can mark an entire class as final by writing the final modifier before the class keyword in its class definition (final class). Any attempt to subclass a final class is reported as a compile-time error.

Apple Doc Inheritence

Blog Post Rating :

Swift Tips: Switch

Please find Swift playground at github.com

This post shares from simple to advance the use of switch cases in swift. These can be enhanced and some time shorthand of more lines of code. I hope you would enjoy them and try to use in your coding style. Please let me know your feedback in the comments if you have any. Happy coding.

Continue reading
Blog Post Rating :

Swift Tips: How to use enumerated() in array

This is very useful if you are trying to manipulate in old school C, C++ way.

Here’s an example:

let array = ["Hulk", "Thor", "Spidy"]

for (index, item) in array.enumerated() {
print("Found \(item) at position \(index)")
}

That will print “Found Hulk at position 0”, “Found Thor at position 1”, and “Found Spidy at position 2”.

Blog Post Rating :