I'm new to backend Swift and thought I'd use Vapor to get up-and-running on a side project fast... I ran vapor new WebServer --template=auth-template, and now I'm trying to figure out what something like return \.email means. For more context, I'm looking in WebServer > Sources > App > Models > Users.swift:

import Authentication
import FluentSQLite
import Vapor

/// Allows users to be verified by basic / password auth middleware.
extension User: PasswordAuthenticatable {
    /// See `PasswordAuthenticatable`.
    static var usernameKey: WritableKeyPath<User, String> {
        return \.email
    }

// ...
}

下面是用户类的定义:

/// A registered user, capable of owning todo items.
final class User: SQLiteModel {
    // {omit extra code} ...

    var email: String

    // {omit extra code} ...

    /// Creates a new `User`.
    init(id: Int? = nil, name: String, email: String, passwordHash: String) {
        // {omit extra code} ...
        self.email = email
        // {omit extra code} ...
    }
}

这个反斜杠点符号是什么意思?

推荐答案

tl;dr:我们来看一下Swift语言参考,果然,这个反斜杠点符号的用法被称为key-path-expression.

(到目前为止,这个问题已经得到了充分的回答.)

A more hands-on approach on how to get to that piece of buried documentation:

从发布的代码中可以看到,User类包含一个名为emailproperty.

请注意,假设您使用的是Xcode,如果将return \.email替换为return \,则会出现编译错误"Expected expression path in Swift key path",因此这是一个提示,表明此反斜杠点符号可能与称为键路径的内容有关.

从密钥路径上的文档中,我们可以看到,我们还可以编写\User.email个(并且您可以在Xcode中try ,而不会出现编译器错误).

Understanding the greater context of what's going on in that code:

所以,从语义上来说,要理解你所看到的usernameKey声明的含义,我们可能需要理解WritableKeyPath是什么.简单地说,从文档中,我们可以看到WritableKeyPath是:"一个支持读取和写入结果值的关键路径."

所以,我们看到usernameKey声明接受WritableKeyPath对象,并返回String,即User.email.

Furthermore, it's apparent that the User class needs this usernameKey property in order to conform to the PasswordAuthenticatable protocol, which was imported on the first line with import Authentication (if you care to explore there, take a look at Dependencies > Auth 2.0.0 > Authentication > Basic > BasicAuthenticatable.swift).

Swift相关问答推荐

如何在Swift中获得与Python相同的HMAC—SHA512签名?

如何使用Swift宏向 struct 体及其init函数添加新成员?

是否在字符串属性上搜索数组和子数组?

我正在try 通过代码设置节中页眉和页脚的高度,但它不起作用

如何使用变量 Select 哪个向量(?)在我的 struct 中密谋吗?

同时具有每个文本的标识符的文本组的可扩展性标识符

如何在SWIFT Memory中处理对VAR数组的更新(对COW感到困惑)

文件命名&NumberForMatter+扩展名&:含义?

如何使用可搜索在搜索栏中搜索包括>或<?

如何判断设备是否为 Vision Pro - Xcode 15 Beta 4

UIView.convert(_ point:to:)的意外行为

在 Swift 中将异步任务包装到 DispatchWorkItem 中以使其可取消?

如何返回一个通过 SwiftUI 中的另一个协议间接继承 View 协议的 struct ?

为什么在Swift中每次调用Decimal类型的formatted()方法都会越来越慢?

Swift:创建用于调用 C 函数的指针数组

在 Swift 中,如何查看 Process() 传递给 shell 的字符串?

如何快速截取 UIView 的屏幕截图?

在 Swift 中为 UIPickerView 设置默认值?

URLComponents.url 为零

将 UIImage 剪成圆形