我有一个 struct ,它可以接受值序列和标量值(数字/字符串/布尔值)作为其泛型类型.我希望它们由两个不同的函数来描述,而不必在运行时进行任何类型判断.我try 使用泛型,但效果不是很好:

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"

预计第二次通话会得到"This is a vector Box"分.

我还try 将第一个函数的泛型限制为Collection类型,但得到了相同的结果.

推荐答案

一种可能性是提供两种描述方法,其中第二种方法在类型约束扩展中定义:

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"

Swift相关问答推荐

Swift UI在视图中排序不同的 struct

如何访问用户选定目录下的(只读)文件?

Variadic泛型与Swift中的值和类型参数包

按下一步后无法让文本字段切换焦点

当计数大于索引时,索引超出范围崩溃

物理主体未与 spritekit Swift 的网格图案上的纹理图像对齐

UIImage和UIimage.pngData返回两个不同的图像

标有@MainActor 的函数中的异步调用是否也在主线程上运行?

Swift 包管理器 Package.resolved 文件末尾的版本是什么意思?

是否可以使用 .task 修饰符更新基于两个值的视图

RxSwift 中 Single.just(...) 和 Observable.just(...) 之间有区别吗?

Swift 有没有办法在不使用 switch 语句的情况下获取关联值?

SwiftUI Grid 中的数组旋转

异步等待不会在项目中触发,但在 Xcode playground 中工作正常

找不到目标AAA的 SPM 工件 - 仅限 Xcode 13.3

Swift - 获取本地日期和时间

如何在 SwiftUI 中打开 ImagePicker?

如何轻松删除领域中的所有对象

如何在 Swift 中重写 setter

如何在 iOS 上的 Swift 中获取 sharedApplication?