Convert Generic Free Function into Array Extension

Convert generic free function into Array extension

Instead of constraining the array extension move the constraint to your method:

extension Array {
func runLengthDecode<T: Equatable>() -> [T] where Element == (element: T, count: Int) {
return flatMap{ repeatElement($0.element, count: $0.count) }
}
}

or simply

extension Array {
func runLengthDecode<T: Equatable>() -> [T] where Element == (element: T, count: Int) {
return flatMap(repeatElement)
}
}

Extension of an array with generic elements

One of the solutions is to create a generic function in the Array extension:

extension Array {
func foo<T>() where Element == AIEvaluation<T> {
...
}
}

Convert generic extension function to simple legacy one

And the only thing i want to do is this: var y = Concat(a, b); and then return an array.

You can't do that unless you're within the same class as the method (or a subclass). You can stop it being an extension method just by removing the this part from the parameter list - but the call would have to be:

var y = GenericExt.Concat(a, b);

Another alternative would be to supply your own ExtensionAttribute class (in the right namespace), and just keep using it as an extension method. The only thing in the framework that is needed for extension methods is that attribute, and you can just copy the declaration out of MSDN. Note that it will then cause problems if you refer to the library from .NET 3.5+ libraries/applications, where the attribute is part of the framework... but if everything is .NET 2, then you should be fine.

Note that the implementation is broken at the moment - at execution time, you're only accepting type arguments which are also arrays... so you'd actually need to pass in an int[][] (with T being int[]) for it to work. You probably just want:

public static T[] Concat<T>(T[] args, T[] args2)
{
T[] array = new T[args.Length + args2.Length];
args.CopyTo(array, 0);
args2.CopyTo(array, args.Length);
return array;
}

But this is a bug in the current implementation which has nothing to do with it being an extension method.

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).")
}
}
}
}

swift extension for generics array

-> [S:M] needs to be put before the where clause.

extension Array {
func merge <S, M> () -> [S: M] where Element == [S: M] {
var res: [S: M] = [:]

self.forEach { element in
element.forEach { obj in
res[obj.key] = obj.value
}
}

return res
}
}

How to properly extend generic return type of array

No need to specify any of those types; just let type inference do its thing:

async function AsyncFN() {
// T is always an array of expected results
const transaction = async() => {
return ['str', {id: 1}]
}

const res = await transaction()
}

With --noImplicityAny and --strictNullChecks this is just as type-safe as the verbose version.

In general, you should rarely need casts, and the use of casts should be a big red flag. TypeScript's type system is very powerful, and it's almost always possible to express types statically in a way that correctly represents what happens at runtime.


Here's what the error message is trying to tell you. The anonymous async function is generic, with a type argument T that must be a subtype of any[], and it returns a value of this type T. The function must, under all circumstances, honour this contract. Let's simplify it a bit without losing the essence:

function myFunc<T extends any[]>(): T {
return ['str']
}

Someone could call this function as:

myFunc<number[]>()

which must return an object of type number[]. But the body of the function doesn't do that; it only ever returns a string[].

Static generic extension for Array for help function for iterated async callbacks

The problem is that

public struct Array<Element> 

is a generic type, and in

Array.iterateObjectList(actions, foreach: { (action, iterationComplete) -> () in
// ...
}, finally: { (objectList, errorList) -> Void in
// ...
})

the compiler cannot infer what Element should be. You could
make it compile as

Array<Action>.iterateObjectList(actions, foreach: { (action, iterationComplete) -> () in
// ...
}, finally: { (objectList, errorList) -> Void in
// ...
})

or even

Array<Int>.iterateObjectList(...)

The array Element is unrelated to your generic placeholder Type,
so any type will do.

But the better solution would be to make the static method an
instance method:

func iterateObjectList(multiplier:Int=1, foreach:(object:Element, (newObject:Element?, error:NSError?) -> Void) -> (), finally: (objectList:[Element], errorList:[NSError]) -> Void)
{
// Your code with `Type` replaced by `Element`,
// and `objectList` replaced by `self`.
// ...
}

and call it on the actions array:

actions.iterateObjectList(foreach: { (action, iterationComplete) -> () in
// ...
}, finally: { (objectList, errorList) -> Void in
// ...
})

Swift Generic array Equatable casting

To define the function only for AAA<Item> if Item is equatable,
simply put the definition into a restricted extension of the class:

class AAA<Item> {
var items = [Item]()
}

extension AAA where Item: Equatable {

func remove(item: Item) {
items.remove(object: item)
}
}

Your approach cannot work because you could still call the remove
method on any AAA<Item> instance, without Item being Equatable.

In other words: You need to restrict the generic type Item
of the class, not the type of the argument of remove().

Generic extension method to map values from one array to another C#

You don't need to write any extension method and you can use "Select" like this:

MyClass[] myClassArray = intArray.Select(x => new MyClass()).ToArray();


Related Topics



Leave a reply



Submit