gpt4 book ai didi

Swift 下标函数 - 允许多种返回类型

转载 作者:行者123 更新时间:2023-11-28 06:10:38 30 4
gpt4 key购买 nike

我正在为 swift 创建一个 Matrix 库,它可以支持可变维矩阵(不仅仅是标准的 2D 矩阵)。

一切顺利,但我遇到了一个问题

我希望 subscript() 函数返回一个值或一个值数组。

所以如果你有一个像这样的简单二维矩阵:

let a : Matrix<Int> = [[1, 2, 3], [4, 5, 6]] // constructs a Matrix 

然后用户像这样在这个矩阵中下标:

b = a[1, 0] //returns 4

但是如果用户这样下标:

b = a[1] //returns [4, 5, 6]

所以基本上我希望这个函数有两种可能的返回类型,具体取决于上下文。我想这样做而不必返回元组/枚举/等。这样它就可以根据矩阵的维度自动推断返回类型。这可能吗?

最佳答案

你很接近,这里有一些东西可以让你开始。

我返回一个可选值以避免因索引范围错误而崩溃。

extension Array {
var bounds : (Int, Int) {
get {
return (0, self.count - 1)
}
}
}

extension Array where Element == Array<Int> {


subscript(first: Int, second: Int) -> Int? {
get {
guard !self.isEmpty else { return nil }
guard first <= bounds.1 else { return nil }
let it = self[first]
guard second <= it.bounds.1 else { return nil }
return it[second]
}
}
}


let one = [[1, 0], [3, 4]]
print(one[1, 0]) // => Optional(3)

关于Swift 下标函数 - 允许多种返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46819660/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com