Be more productive building your mobile apps
One of the best features of both Swift and Objective-C, in my opinion, is extensions. They enable you to add new methods to any class and the whole project will be able to call them without additional inheritance and overloading.
As a mobile developer I work with both iOS and Android, and I very often see Android functions and methods which are shorter, cleaner and more understandable than in Swift. Using extensions, some of these methods can be ported to Swift. Plus with several new methods (extensions) we’ll get a short, clean and easily maintainable code in Swift.
I’ll use Swift, but all these extensions can be migrated to Objective-C or used with Objective-C directly, without conversion.
In 99% of the cases when I trim String in Swift, I want to remove spaces and other similar symbols (for example, new lines and tabs).
This simple extension does the trick:
import Foundation
extension String {
var trimmed: String {
self.trimmingCharacters(in: .whitespacesAndNewlines)
}
mutating func trim() {
self = self.trimmed
}
}
Usage:
var str1 = " a b c d e \n"
var str2 = str1.trimmed
str1.trim()
#xcode #ios #swift #programming