gpt4 book ai didi

swift - 简单 Int 和错误

转载 作者:搜寻专家 更新时间:2023-11-01 07:17:53 24 4
gpt4 key购买 nike

我刚开始使用 Swift,它来自 Objective-C。我有这一行:

self.collectionView?.insertItems(at: [IndexPath.init(row: (self.flights.count -1), section: 0)])

我收到一条错误消息:“count”之后的 Expected ',' separator

为什么我不能做一个简单的求和,计数-1? Swift 的一个小怪癖我还没有学会,或者是早上太早了......

最佳答案

引用 Apple 的“Lexical Structure”文档:

The whitespace around an operator is used to determine whether an operator is used as a prefix operator, a postfix operator, or a binary operator. This behavior is summarized in the following rules:

  • If an operator has whitespace around both sides or around neither side, it is treated as a binary operator. As an example, the +++ operator in a+++b and a +++ b is treated as a binary operator.

  • If an operator has whitespace on the left side only, it is treated as a prefix unary operator. As an example, the +++ operator in a +++b is treated as a prefix unary operator.

  • If an operator has whitespace on the right side only, it is treated as a postfix unary operator. As an example, the +++ operator in a+++ b is treated as a postfix unary operator.

  • If an operator has no whitespace on the left but is followed immediately by a dot (.), it is treated as a postfix unary operator. As an example, the +++ operator in a+++.b is treated as a postfix unary operator (a+++ .b rather than a +++ .b).

注意:++-- 已从 Swift 3 中删除。有关更多信息资料查询0004 Swift evolution proposal .

表示 self.flights.count -1 中的减号运算符被视为前缀一元运算符(第二条规则)。

为了更清楚,编译器将 self.flights.count -1 读取为:self.flights.count,旁边有一个负数,但不是减法运算。通过应用第二条规则,减号是 1 的前缀一元运算符。

显然,您希望编译器将减号运算符视为二元运算符,因此您应该做的是在减号两边添加空格(应用第一条规则):

self.collectionView.insertItems(at: [IndexPath.init(row: (flights.count - 1), section: 0)])

希望这对您有所帮助。

关于swift - 简单 Int 和错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40971207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com