iOS手势识别器遍历不同的状态。在第一个开始状态下捕获参考状态是常见的(至少对我来说)。在ObjectiveC中,可能看起来像:
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
[TestFixture]
public class SqlStringExtensionsTests
{
[Test]
public void ValidateSql_InvalidSql_ReturnsErrorMessages()
{
// this example doesn't contain "," between the field names
string invalidSql = "SELECT /*comment*/ " +
"CustomerID AS ID CustomerNumber FROM Customers";
IEnumerable<string> results = invalidSql.ValidateSql();
Assert.AreNotEqual(0, results.Count());
}
[Test]
public void IsValidSql_ValidSql_ReturnsTrue()
{
string validSql = "SELECT /*comment*/ " +
"CustomerID AS ID, CustomerNumber FROM Customers";
bool result = validSql.IsValidSql();
Assert.AreEqual(true, result);
}
[Test]
public void IsValidSql_InvalidSql_ReturnsFalse()
{
// this example doesn't contain "," between the field names
string invalidSql = "SELECT /*comment*/ "+
" CustomerID AS ID CustomerNumber FROM Customers";
bool result = invalidSql.IsValidSql();
Assert.AreEqual(false, result);
}
}
但是Swift没有静态函数变量来保存函数执行之间的值。我可以在类级别将这些变量转换为- (void)pan:(UIPanGestureRecognizer *)pan {
static NSTimeInterval originalBegin;
static NSTimeInterval originalEnd;
static CGFloat originalYOffset;
if (pan.state == UIGestureRecognizerStateBegan) {
originalBegin = self.timeAxis.begin;
originalEnd = self.timeAxis.end;
originalYOffset = self.yOffset;
}
...
}
s,但是它会污染对象的变量空间,仅适用于仅附加到特定识别器的变量。
是否有Swift习惯方式在本地捕获此模式?或者这是Swift与UIKit摩擦的领域之一。
答案 0 :(得分:2)
在Swift中,您可以在函数中嵌套struct,class或enum定义,并在运行之间保持静态状态。例如:
func run() {
enum State { static var counter = 0 }
State.counter += 1
print(State.counter)
}
run()
run()
run()