Home > OS >  Select between sequence and non-sequence generic functions in struct
Select between sequence and non-sequence generic functions in struct

Time:01-10

I have a struct that can take in both sequences of values and scalar values (numbers/strings/booleans) as its generic type. I'd like for them to be described by two different functions without having to do any type checking at runtime. I tried using generics but it didn't quite work :

import Foundation

struct Box<T>: CustomStringConvertible {
    static func descriptor<T: Sequence>(box: Box<T>) -> String {
        return "This is a vector Box"
    }
    
    static func descriptor<T>(box: Box<T>) -> String {
        return "This is a scalar Box"
    }
    
    var description: String {
        return Box<T>.descriptor(box: self)
    }
}

let b = Box<Double>()
b.description                              // "This is a scalar Box"
let c = Box<[Double]>()
c.description                              // "This is a scalar Box"

Expected to get "This is a vector Box" for the second call.

I also tried constraining the generic of the first function to be of type Collection but got the same result.

CodePudding user response:

One possibility is to provide two description methods, where the second is defined in a type-constrained extension:

struct Box<T>: CustomStringConvertible {
    var description: String {
        return "This is a scalar Box"
    }
}

extension Box where T: Sequence {
    var description: String {
        return "This is a vector Box"
    }
}

let b = Box<Double>()
print(b.description)    // "This is a scalar Box"
let c = Box<[Double]>()
print(c.description)    // "This is a vector Box"
  • Related