如何定义定制的下标数组运算符,该运算符使数组元素“出现".如果有必要 [英] how to define a custom subscripting array operator which makes array elements "spring into existence" if necessary

查看:104
本文介绍了如何定义定制的下标数组运算符,该运算符使数组元素“出现".如果有必要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将运算符func添加到Swift类下标方法

was it possible to add operator func to Swift class subscript method

var x = ["dkfkd", "dkff"]
x[2] ??=  "mmmm" // equal to x[2] = x[2] ?? "mmmm"

推荐答案

这与下标运算符无关,而是一个有关如何定义??=运算符的问题.您可以执行此操作,但是它可能无法达到您期望的方式.

This isn’t related to the subscript operator, but more a question of how to define a ??= operator. Which you can do, but it might not work quite the way you expect.

这是可能的实现方式:

// first define the ??= operator
infix operator ??= { }

// then some pretty standard logic for an assignment
// version of ??
func ??=<T>(inout lhs: T?, rhs: T) {
    lhs = lhs ?? rhs
}

这可以编译,并且可以像您期望的那样工作:

This compiles, and works as you might be expecting:

var i: Int? = 1

i ??= 2   // i unchanged

var j: Int? = nil

j ??= 2  // j is now Some(2)

它也可以与下标结合使用

It will also work in combination with subscripts:

var a: [Int?] = [1, nil]

a[1] ??= 2

a[1]  // is now Some(2)

我说,由于类型的原因,这可能无法完全按预期工作. a ?? b具有可选的a,如果它是nil,则返回默认值b. 但是,它返回一个非可选值.这就是??的重点.

I say this might not work completely as expected because of the types. a ?? b takes an optional a, and if it’s nil, returns a default of b. However it returns a non-optional value. That’s kinda the point of ??.

另一方面,??= 不能执行此操作.因为已经确定左侧是可选的,并且赋值运算符不能仅更改值的类型.因此,尽管在nil的情况下它将替换可选值内的值,但不会将类型更改为非可选.

On the other hand, ??= cannot do this. Because the left-hand side is already determined to be optional, and an assignment operator cannot change the type only the value. So while it will substitute the value inside the optional in the case of nil, it won’t change the type to be non-optional.

PS ??=函数完全编译的原因是因为如果需要,非可选值(即从lhs ?? rhs返回的内容)会隐式升级为可选值,因此lhs ?? rhs的类型为,可以分配给类型为T?lhs.

PS the reason the ??= function compiles at all is because non-optional values (i.e. what you will get back from lhs ?? rhs) are implicitly upgraded to optional values if necessary, hence lhs ?? rhs, of type T, can be assigned to lhs, which is of type T?.

这篇关于如何定义定制的下标数组运算符,该运算符使数组元素“出现".如果有必要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆