[英]Assign to variable or return it right away doesn't work
If I do this: 如果我这样做:
func myFunc() -> NSRange{
var range = s.rangeOfString(searchText, options: .CaseInsensitiveSearch)
return s.rangeOfString(searchText, options: .CaseInsensitiveSearch)
}
I get an error that says there's extra arguments in the second call. 我得到一个错误,说第二次调用中有额外的参数。 But they are exactly the same!
但它们完全一样!
On the other hand, this works fine: 另一方面,这很好用:
func myFunc() -> NSRange{
var range = s.rangeOfString(searchText, options: .CaseInsensitiveSearch)
return range
}
My question is implicit. 我的问题是隐含的。 So here it is: why swift compiler doesn't get satisfied with the first option and instead it makes me assign the return of the function to a variable first?
所以这就是:为什么swift编译器不满足于第一个选项,而是让我首先将函数的返回值分配给变量?
If that works for you, here's my full code: 如果这对你有用,这是我的完整代码:
var a: [MyObject] = []
array = a.filter{
var b = ($0 as MyObject).molecule.name
var s: NSString = b as NSString
var range = s.rangeOfString(searchText, options: .CaseInsensitiveSearch)
return s.rangeOfString(searchText, options: .CaseInsensitiveSearch)
return range.location != -1
}
The problem is different than what Swift reports. 问题与Swift报道的不同。 The error reporting in Swift can be pretty strange at times.
Swift中的错误报告有时会非常奇怪。
The real problem is that filter
expects a boolean value to be returned, representing if that item should be included. 真正的问题是
filter
需要返回一个布尔值,表示是否应该包含该项。 But rangeOfString
returns an NSRange
. 但
rangeOfString
返回NSRange
。
So if you return an expression that yields a boolean value, it works fine. 因此,如果返回一个产生布尔值的表达式,它可以正常工作。
return s.rangeOfString(
searchText,
options: .CaseInsensitiveSearch
).location != NSNotFound
Which is why your first example works fine. 这就是你的第一个例子正常工作的原因。 You say this function returns an
NSRange
and then you return an NSRange
so it works! 你说这个函数返回一个
NSRange
,然后你返回一个NSRange
就可以了!
func myFunc() -> NSRange{
var range = s.rangeOfString(searchText, options: .CaseInsensitiveSearch)
return s.rangeOfString(searchText, options: .CaseInsensitiveSearch)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.