Creating an extension to filter nils from an Array in Swift

As of Swift 2.0, you don’t need to write your own extension to filter nil values from an Array, you can use flatMap, which flattens the Array and filters nils: let optionals : [String?] = [“a”, “b”, nil, “d”] let nonOptionals = optionals.flatMap{$0} print(nonOptionals) Prints: [a, b, d] Note: There are 2 flatMap functions: One … Read more

How to define initializers in a protocol extension?

As you can see this doesn’t work under these circumstances because when compiling, one has to make sure that all properties are initialized before using the struct/enum/class. You can make another initializer a requirement so the compiler knows that all properties are initialized: protocol Car { var wheels : Int { get set } // … Read more

Extend array types using where clause in Swift

If you want to extend only array with specific type. You should extend _ArrayType protocol. extension _ArrayType where Generator.Element == Int { func doSomething() { … } } If you extend Array you can only make sure your element is conformed some protocol else. i.e: extension Array where Element: Equatable { func doSomething() { … … Read more

How to create swift class for category?

In Swift, you can use Extensions to add new functionality to existing classes, structs and enumeration types. They differ from Objective-C categories in a few ways, mainly: They aren’t named You don’t need to import an Extension explicitly. If you define an extension to add new functionality to an existing type, the new functionality will … Read more

Can Objective-C code call Swift class extensions?

You can write a Swift extension and use it in Objective-C code. Tested with Xcode 6.1.1. All you need to do is: create your extension in Swift (@objc annotation needed since Swift 4.0.3) #import “ProjectTarget-Swift.h” in your Objective-C class (where “ProjectTarget” represents the XCode target the Swift extension is associated with) call the methods from … Read more

Overriding methods in Swift extensions

Extensions cannot/should not override. It is not possible to override functionality (like properties or methods) in extensions as documented in Apple’s Swift Guide. Extensions can add new functionality to a type, but they cannot override existing functionality. Swift Developer Guide The compiler is allowing you to override in the extension for compatibility with Objective-C. But … Read more

How to define optional methods in Swift protocol?

1. Using default implementations (preferred). protocol MyProtocol { func doSomething() } extension MyProtocol { func doSomething() { /* return a default value or just leave empty */ } } struct MyStruct: MyProtocol { /* no compile error */ } Advantages No Objective-C runtime is involved (well, no explicitly at least). This means you can conform … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)