我有课
public class Thing
像这样
var blah:Thing
blah.name = "text"
我想到,当右侧的项目是一个字符串时,如果我能够“覆盖等号”,那就太棒了。
那么你就可以拥有
var blah:Thing
var x:Thing
blah = "text" // Swift knows I mean blah.name = "text"
blah = x // Swift knows I mean blah becomes x as normal
我是否遗漏了一些明显的东西?怎么办?
请注意,您当然可以接管下标操作,使用
public subscript
这太棒了。你能代替“=”等号吗?
最佳答案
You can't override the =
operator in Swift:
NOTE
The tokens
=
,->
,//
,/*
,*/
,.
, the prefix operators<
,&
, and?
, the infix operator?
, and the postfix operators>
,!
, and?
are reserved. These tokens can’t be overloaded, nor can they be used as custom operators.
它可以用 C++ 完成,主要是由于需要手动内存管理。感谢 ARC,这在 Swift 中是不必要的,它只会给你的代码添加不必要的烟雾和镜子,并带来各种令人困惑的隐式行为。
关于Swift 3,自定义 "="等于运算符 ? (不相等, "=="),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40388065/