How can I extend typed Arrays in Swift?
For extending typed arrays with classes, the below works for me (Swift 2.2). For example, sorting a typed array:
class HighScoreEntry {
let score:Int
}
extension Array where Element == HighScoreEntry {
func sort() -> [HighScoreEntry] {
return sort { $0.score < $1.score }
}
}
Trying to do this with a struct or typealias will give an error:
Type 'Element' constrained to a non-protocol type 'HighScoreEntry'
Update:
To extend typed arrays with non-classes use the following approach:
typealias HighScoreEntry = (Int)
extension SequenceType where Generator.Element == HighScoreEntry {
func sort() -> [HighScoreEntry] {
return sort { $0 < $1 }
}
}
In Swift 3 some types have been renamed:
extension Sequence where Iterator.Element == HighScoreEntry
{
// ...
}
How can I make a extension for array of specific type in Swift
for say the specific type is S
extension CollectionType where Generator.Element == S {
}
CollectionType Protocol
Extending Arrays of Arrays - Swift 4.1
You can extend in either way
extension Array where Element == Int {
func someIntegers() {
}
}
extension Array where Element == Array<String> {
func someStrings() {
}
}
and call like this anywhere,
[0, 1, 2].someIntegers()
[["hi"]].someStrings()
Swift Array extension with generic items
Try this:
import Foundation
protocol Section {
associatedtype InfoT: Equatable
associatedtype ItemsT: Equatable
var info: InfoT? { get }
var items: [ItemsT] { get }
}
extension Array where Element: Section {
// Just dummy example function:
func debugDummy() {
for section in self {
let info = section.info
print("section info: \(String(describing: info)).")
for item in section.items {
print("item: \(item).")
}
}
}
}
Extension of Set where element is an Array of a specific type
Since you cannot make Array<NSOperation>
conform to Hashable
you'll have to make a small wrapper-struct.
E.g.
struct NSOperationList {
var operations = [NSOperation]()
}
and then build all functionality you need on top of NSOperationList
.
So if you want to add support for Set
:
extension NSOperationList: Hashable {
var hashValue: Int {
return operations.reduce(0) { $0 ^ $1.hashValue }
}
}
func == (a: NSOperationList, b: NSOperationList) -> Bool {
return a.operations == b.operations
}
Extending typed array by conforming to a protocol in Swift 2
You can't apply a lot of logic to conformance. It either does or does not conform. You can however apply a little bit of logic to extensions. The code below makes it easy to set specific implementations of conformance. Which is the important part.
This is used as a typed constraint later.
class SomeType { }
This is your protocol
protocol SomeProtocol {
func foo()
}
This is an extension of the protocol. The implementation of foo()
in an extension of SomeProtocol
creates a default.
extension SomeProtocol {
func foo() {
print("general")
}
}
Now Array
conforms to SomeProtocol
using the default implementation of foo()
. All arrays will now have foo()
as a method, which is not super elegant. But it doesn't do anything, so it's not hurting anyone.
extension Array : SomeProtocol {}
Now the cool stuff:
If we create an extension to Array
with a type constraint for Element
we can override the default implementation of foo()
extension Array where Element : SomeType {
func foo() {
print("specific")
}
}
Tests:
let arrayOfInt = [1,2,3]
arrayOfInt.foo() // prints "general"
let arrayOfSome = [SomeType()]
arrayOfSome.foo() // prints "specific"
How to extend Array for generic type?
You can declare a generic parameter in initializer definition.
extension Array {
init<T>(node: LinkedNode<T>)
where Element == LinkedNode<T>
{
var result = [LinkedNode<T>]()
node.traverseList { result.append($0) }
self = result
}
}
Related Topics
Swift Can't Infer Generic Type When Generic Type Is Being Passed Through a Parameter
Nested Types in Swift - What Is the Good Practice
Swiftui Label Text and Image Vertically Misaligned
Load Desktop Version Wkwebview iOS 9
In Swift, Does Int Have a Hidden Initializer That Takes a String
How to Create a Multi Line Text Field in Swiftui for MACos
Swift: Detecting an Unexpected Nil Value in a Non-Optional at Runtime: Casting as Optional Fails
Map or Reduce with Index in Swift
How to Get Indexpath.Row in Cell.Swift
How to Identify Uppercase and Lowercase Characters in a String with Swift
Redeclaring Members in an Extension Hides the Original Member *Sometimes*. Why
Swift Operator "*" Throwing Error on Two Ints
Alamofire Type 'Parameterencoding' Has No Member 'Url' Swift 3
Controlling Size of Texteditor in Swiftui
Nsurlerrordomain with Code=-1100
Subtle Cast Warning When Using SQLite.Swift ... Binding? to Any
Nothing Prints Out in the Console in Command Line Tool Xcode