ios - 成员类型的快速重载运算符

标签 ios swift overloading

我对 swift 中的运算符重载有疑问。 在我的代码中,我有一个这样的结构:

struct Position {

///The horisontal index for a chessboard [A-H]
let horisontal : String

///The vertical index for a chessboard [1-8]
let vertical : Int
}

接下来我需要的是一种以索引 +- 某个整数的方式更改水平索引的方法。然后我要做的是重载“+”运算符,如下所示:

func + (left: Position.horisontal, right: Int) -> Bool {
      //Some implementation in here
}

然后我的世界就崩溃了。编译器告诉我:“'horisontal 不是'Position'的成员类型” 在这种情况下,我不知道什么可以帮助我?为什么编译器拒绝承认“水平”的存在?我还能做些什么来实现 String 和 Int 之间的加法?

备注 请注意,这工作得很好,但我认为这不符合运算符重载的良好精神:

func + (left: String, right: Int) -> Bool {
      //Some implementation in here
}

最佳答案

Why the compiler refuses to acknowledge the existence of 'horisontal'?

因为 horisontal [原文如此] 不是类型,所以它是 Position 类型的成员。

更合适的解决方案是为行和列位置定义一个封闭的enum

关于ios - 成员类型的快速重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27001665/

相关文章:

android - iOS 相当于 Android 布局权重是多少?

arrays - 如何将自定义对象附加到 Swift 中的数组?

typescript - 泛型类的可选方法参数的类型

c++ - 具有相同参数的多种类型的函数

php - 核心数据快速同步mysql数据库

ios - iOS 应用程序获得批准后在 iTunes Connect 中编辑屏幕截图

ios - 没有 Storyboard和segue的快速委托(delegate)问题

c++ - 公共(public)算子新建,私有(private)算子删除 : getting C2248 "can not access private member" when using new

ios - 如何使线条边缘平滑?

ios - 应用启动时等待 Core Location 的当前位置