Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Types 定义对类型而不是值进行操作的Swift函数_Types_Swift_Optional_Type Variables - Fatal编程技术网

Types 定义对类型而不是值进行操作的Swift函数

Types 定义对类型而不是值进行操作的Swift函数,types,swift,optional,type-variables,Types,Swift,Optional,Type Variables,在Swift中,?运算符将类型作为参数,而不是值: var z = 42? // won't create an Optional<Int> and won't compile var z : Int? = 42 // ? takes Int and give a Optional<Int> var z=42?//不会创建可选的,也不会编译 变量z:Int?=42 // ? 取Int并给出一个可选值 我怎样才能创建自己的函数,或者使用类型而不是值的运算符?您想要实现的

在Swift中,
运算符将
类型
作为参数,而不是值:

var z = 42? // won't create an Optional<Int> and won't compile
var z : Int? = 42 // ? takes Int and give a Optional<Int>
var z=42?//不会创建可选的,也不会编译
变量z:Int?=42 // ? 取Int并给出一个可选值

我怎样才能创建自己的函数,或者使用类型而不是值的运算符?

您想要实现的是不可能的

但是有一个解决方法:您可以创建一个自定义运算符,在给定一个文本或变量时,将其转换为可选的。Swift不允许在自定义运算符中使用
字符,我选择的是随机组合,但请随意使用您自己的:

postfix operator >! {}

postfix func >! <T>(value: T) -> T? {
    return value as T?
}

不是对类型进行操作的运算符,它是Swift在
可选
之上的“语法糖”的一部分。换句话说,当编译器在类型名后看到
时,它知道该做什么。如果希望编写这样的运算符,则需要修改编译器。
10>! // {Some 10}

"Test">! // {Some "Test"}