logo
down
shadow

Swift 3 Generics: How to Find The Common Set of Two Generic Arrays


Swift 3 Generics: How to Find The Common Set of Two Generic Arrays

By : hungdt
Date : November 20 2020, 11:01 PM
hop of those help? I am trying to find the common set of two generic arrays in Swift 3. I got a type compatibility error with the code below. This happens on the line where I am trying to add an element to the commons array: "error: cannot invoke 'append' with an argument list of type '(T.Iterator.Element)' commonSet.append(lhsItem)" , Solution for Hashable types
code :
extension Sequence where Iterator.Element: Hashable {
    func intersect<T: Sequence>(with other: T) -> [Iterator.Element]
    where T.Iterator.Element == Self.Iterator.Element {
        let otherSet = Set(other)
        return self.filter(otherSet.contains)
    }
}
extension Sequence where Iterator.Element: Comparable {
    func intersect<T: Sequence>(with other: T) -> [Iterator.Element]
    where T.Iterator.Element == Self.Iterator.Element {
        let arrayA = self.sorted()
        let arrayB = other.sorted()
        var indexA = 0, indexB = 0

        var intersection: [Iterator.Element] = []
        while indexA < arrayA.count && indexB < arrayB.count {
            let a = arrayA[indexA]
            let b = arrayB[indexB]

            if      (a < b) { indexA += 1 }
            else if (b < a) { indexB += 1 }
            else /* implied: a == b */ {
                intersection.append(a)
                indexA += 1
                indexB += 1
            }
        }

        return intersection;
    }
}


Share : facebook icon twitter icon
Swift Generics: More specialized than generic?

Swift Generics: More specialized than generic?


By : CilVine
Date : March 29 2020, 07:55 AM
wish helps you Unlike C++, Swift does not deal with generics by substituting the concrete types at the call site and making a non-generic copy (at least in general it doesn't - as an optimization that's allowed, but I digress)
Swift deals with genericity by passing in metadata information describing the actual types at each invocation into one master function, which then uses metadata-provided entry points to manipulate your objects
code :
metadata[Initializable]->defVal(metadata)
<T: protocol<Initializable,Multipliable>>
Swift Generics will not instantiate generic when using inheritance

Swift Generics will not instantiate generic when using inheritance


By : user2677212
Date : March 29 2020, 07:55 AM
should help you out What you trying to achieve is passing an instance of Berry and getting another instance of Berry?
If so, following code should work:
code :
class Alpha {

    required init() { } // ← YOU NEED THIS

    func printme() {
        println("I'm alpha")
    }
}
class Berry : Alpha {
    override func printme() {
        println("I'm berry")
    }
}

func myFunc<T:Alpha>(v:T) -> T {
    return v.dynamicType()
}
// This also works:
/*
func myFunc<T: Alpha>(v:T) -> T {
    return (T.self as T.Type)()
}
*/

let a = myFunc(Berry())
a.printme() // -> I'm berry
class Alpha {
    required init() { }
    func printme() {
        println("alpha")
    }
}
class Berry : Alpha {
    override func printme() {
        println("berry")
    }
}

func myFunc<T:Alpha>(v:T.Type) -> T {
    return v()
}

let a = myFunc(Berry)
a.printme()
Arrays of Generics in Swift

Arrays of Generics in Swift


By : user3522941
Date : March 29 2020, 07:55 AM
will be helpful for those in need There is a way - sort of - to do what you want - kind of. There is a way, with protocols, to eliminate the type restriction and still get the result that you want, kind of, but it isn't always pretty. Here is what I came up with as a protocol in your situation:
code :
protocol MyProtocol {
    func getValue() -> Self 
}

extension Int: MyProtocol {
    func getValue() -> Int {
        return self
    }
}

extension Double: MyProtocol {
    func getValue() -> Double {
        return self
    }
}
class Container {
    var values: [MyProtocol]

    init(_ values: MyProtocol...) {
        self.values = values
    }

    func myMethod() -> [MyProtocol] {
        return values
    }
}
var containers = [Container]()

containers.append(Container(1, 4, 6, 2, 6))
containers.append(Container(1.2, 3.5))

for container in containers {
    println(container.myMethod())
}

//  Output: [1, 4, 6, 2, 6]
//          [1.2, 3.5]
extension String: MyProtocol {
    func getValue() -> String {
        return self
    }
}
let container = Container(1, 4.2, "no kidding, this works")
protocol ContainerProtocol {
    func myMethod() -> [MyProtocol]
}

class Container<T: MyProtocol>: ContainerProtocol {
    var values: [T] = []

    init(_ values: T...) {
        self.values = values
    } 

    func myMethod() -> [MyProtocol] {
        return values.map { $0 as MyProtocol }
    }
}
let containers: [ContainerProtocol] = [Container(5, 3, 7), Container(1.2, 4,5)]

for container in containers {
    println(container.myMethod())
}
Putting two generic Arrays into one Swift Dictionary with Generics

Putting two generic Arrays into one Swift Dictionary with Generics


By : gomezcatalina
Date : March 29 2020, 07:55 AM
wish of those help Elaborating on the answer from @RobNapier, here is a similar approach that uses enum for both, keys and values of the dictionary:
code :
enum Key: Equatable, Hashable {
    case IntKey(Int)
    case StringKey(String)

    var hashValue: Int {
        switch self {
        case .IntKey(let value)     : return 0.hashValue ^ value.hashValue
        case .StringKey(let value)  : return 1.hashValue ^ value.hashValue
        }
    }

    init(_ value: Int)    { self = .IntKey(value) }
    init(_ value: String) { self = .StringKey(value) }
}

func == (lhs: Key, rhs: Key) -> Bool {
    switch (lhs, rhs) {
    case (.IntKey(let lhsValue),    .IntKey(let rhsValue))    : return lhsValue == rhsValue
    case (.StringKey(let lhsValue), .StringKey(let rhsValue)) : return lhsValue == rhsValue
    default: return false
    }
}

enum Value {
    case IntValue(Int)
    case StringValue(String)

    init(_ value: Int)    { self = .IntValue(value) }
    init(_ value: String) { self = .StringValue(value) }
}

var dict = [Key: Value]()

dict[Key(1)] = Value("One")
dict[Key(2)] = Value(2)
dict[Key("Three")] = Value("Three")
dict[Key("Four")] = Value(4)
Swift Codable with Generics, holding common data from responses

Swift Codable with Generics, holding common data from responses


By : user3377689
Date : March 29 2020, 07:55 AM
help you fix your problem I will try to explain what I want to do in a best possible way, just like I tried while Googling for the last couple of days. , What you're looking for here is a protocol.
code :
protocol ErrorProviding {
    var error: String? { get }
}
struct APIResponse<T: ErrorProviding> {
    var value: T?
    var error: String? { value?.error }
}
extension Root1: ErrorProviding {
    var error: String? { errors.first }
}
extension Root2: ErrorProviding {}
Related Posts Related Posts :
  • update field of array object inside nested object
  • Sending a row of a multidimensional array to a worksheet
  • Typescript Array insert non-duplicate item
  • how to ascending sort a multiple array of SPARK RDD by any column in scala?
  • Casting an anonymous array initializer list
  • creating hash from array in perl
  • Average of each two columns in an array
  • Calculate subtotal using tuples and 3 UIPickerviews
  • Matlab: insert multiple elements at specified positions
  • how to get Int from elements of dictionary array. xcode
  • Python/Pandas: Array (back) to DataFrame
  • Permanent Data and Prepare For Segue
  • Difference between array<<element and array.push(element)? or string<<"something" and string+"
  • Index array with multiple ranges
  • In VBA how do I get the "ActiveChart.FullSeriesCollection(i).Values" to point to a specific line of a 2 dimens
  • List in dictionary as a template definition
  • How to sort string array in descending order in Bash?
  • Pass variable with spaces into array
  • How to unpack an array from php into Swift via JSON
  • How to insert data in codename one db using prepared statement?
  • Find kth smallest element from two sorted arrays
  • How to filter through multiple "Arrays" at once?
  • Array inside a type in julia
  • PowerShell dictionary of arrays?
  • Excel VBA Non-Contiguous Array User Defined Function Fix
  • Skip to next in array for batch based off of IF condition
  • Efficient to delete all substrings of other elements within an array in Ruby
  • Go: Loops over sorted array, sort.Sort used as value
  • Finite difference derivative of an array
  • How to convert multidimensional array into a 2 dimensional array?
  • ECMAScript 2015 Features (Math + Number + String + Object APIs)?
  • match, index, and concatenate to just one cell
  • Push directory timestamps into an array sorted by date in bash
  • Go: Deserialize array string
  • How do I check if two string arrays are equal?
  • How to have upper case methods in ruby
  • Array of structs with this Dictionary in Swift
  • Check one array's elements contains in another array
  • VBA part of two dimensional Array into combobox.List
  • convert a csv file to json where one of the fields can be converted into an array
  • Generate all unique items in a list using right shift bitwise operator
  • How to deserialize dodgy JSON (with improperly quoted strings, and missing brackets)?
  • $lookup result sorted using a key from another array
  • Slicing Multidimensional Array by a variable
  • Find if given longitude, latitude pair lies in any of the polygon in MongoDB
  • Need help sorting file list in perl based on datestamp in filename
  • Searching a string array of names and grades and listing names associated with grade
  • Golang: array is empty after call a method that adds items to the array
  • Fill an array from keyboard in Java
  • How to save 2d array data permanently using userdefaults.standard
  • how to access an arraylist with json objects in a repeat control
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com