首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在swift中重载赋值运算符

如何在swift中重载赋值运算符
EN

Stack Overflow用户
提问于 2015-04-30 17:38:30
回答 2查看 10.3K关注 0票数 28

我想覆盖CGFloat的'=‘运算符,如下所示:

func = (inout left: CGFloat, right: Float) {
    left=CGFloat(right)
}

因此,我可以执行以下操作:

var A:CGFloat=1
var B:Float=2
A=B

这可以做到吗?我得到错误Explicitly discard the result of the closure by assigning to '_'

EN

回答 2

Stack Overflow用户

发布于 2016-02-18 16:46:54

你不能重写赋值,但你可以在你的情况下使用不同的运算符。例如&=运算符。

func &= (inout left: CGFloat, right: Float) {
    left = CGFloat(right)
}

因此,您可以执行以下操作:

var A: CGFLoat = 1
var B: Float = 2
A &= B

顺便说一句,swift中存在运算符&+&-&*。它们表示没有溢出的C风格的操作。More

票数 12
EN

Stack Overflow用户

发布于 2021-04-15 17:29:02

这不是operator loading方法。但是结果可能是你所期望的。

// Conform to `ExpressibleByIntegerLiteral` and implement it
extension String: ExpressibleByIntegerLiteral {
    public init(integerLiteral value: Int) {
        // String has an initializer that takes an Int, we can use that to
        // create a string
        self = String(value)
    }
}

extension Int: ExpressibleByStringLiteral {
    public init(stringLiteral value: String) {
        self = Int(value) ?? 0
    }
}

// No error, s2 is the string "4"
let s1: Int = "1"
let s2: String = 2

print(s1)
print(s2)
print(s1 + 2)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29964177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档