我想要将一个可编码的 struct 转换成键值对,这样我就可以把它写到CSV中的一行中,这样我就可以用EXCEL或Apple数字来表示它.我需要在CSV的一些单元格,以参考为基础的计算.

例如,假设我有A1作为收入,A2作为支出,我想让A3作为净yield 或"=A1-A2"

struct FinanceSummary {
  var expense: Decimal
  var revenue: Decimal

  var lineReference: Int { #line + 2 } // + 2 for the 2 lines below before key pairs
  func keyPairs(row: Int) -> KeyValuePairs<String, String> {
    [
      "expense": "\(expense)",
      "revenue": "\(revenue)",
      "income": "=A\(#line - lineReference - 1) - A\(#line - lineReference - 2)"
    ]
  }
}

然而,在我过go 可以使用#line来获取行号的地方,当我try 时,我得到了一个错误:#line directive was renamed to #sourceLocation,当我使用#sourceLocation时,我得到了另一个错误:Expected '(' in #sourceLocation directive,因为编译器希望我用文件和行号来初始化源位置.但是,我不想告诉编译器,我在什么文件和行上.我想让编译器告诉我.

推荐答案

该错误消息具有误导性.显然,#line指令不能是计算(computed)属性主体中的第一个表达式(我不知道为什么).作为一种解决办法,您可以编写

var lineReference: Int { return #line + 2 }

var lineReference: Int { 2 + #line }

或 simply use a st或ed property instead:

let lineReference = #line + 2

Swift相关问答推荐

RealityKit(VisionOS)中的PhysicBodyComponent和DragGesture

异步/等待函数的XCTAssertThrowsError

可以';t在标记为@Observable的类上使用属性包装

Swift 扩展:通过方法重载增强现有类

是否可以限制 ExpressibleByIntegerLiteral struct 的初始值?

如何让默认函数参数引用另一个函数参数?

标有@MainActor 的函数中的异步调用是否也在主线程上运行?

覆盖一个子元素的 HStack 对齐方式

Firebase removeObserver 在 Swift 5 中不起作用

LeetCode 249. 分组移位字符串

如何在 SwiftUI 中将图像传递到 2 个视图

如何在 ZStack 中单独下移卡片?

iOS 判断应用程序是否可以访问麦克风

EXC_BREAKPOINT 崩溃的原因范围

Swiftwhere数组扩展

Swift 中的 CommonHMAC

两个 Date 对象之间的所有日期 (Swift)

Swift 2.0 按属性对对象数组进行排序

Swift performSegueWithIdentifier 不起作用

将 UIImage 剪成圆形