Type mismatch, expected "Swift.Array<T>"

swift

(wdb) #1

The code snippet compiles happily in Xcode 9 but fails in Fire. Am I doing something wrong?

// Add to models to filter them with search query strings
protocol Filterable {
	func match(query: String) -> Bool
}

func filtered<T>(array: [T], query: String) -> [T] {
	let cleanQuery = query.trimmingCharacters(in: CharacterSet.whitespaceAndNewlineCharacterSet)
	guard !cleanQuery.isEmpty else { return array }

	return array.filter({ (o) -> Bool in.  // <- error here
		if let o = o as? Filterable {
			return o.match(query: cleanQuery)
		} else {
			// if object isn't Filterable, always include it
			return true
		}
	})
}

(marc hoffman) #2

Looks like it should (aside from that extra period after in). filter is defined in SBL as

	public func filter(_ includeElement: (T) -> Bool) -> ISequence<T> { // we deliberatey return a sequence, not an array, for efficiency and flexibility.

what platform? can you send me a complete project that shows this?

thanx


(wdb) #3

Sure, I just created a new project and added the file. Removed the bits which aren’t supported yet. I have attached the project (it’s just two files). I didn’t get it working with the latest 9.3 beta.

App2.zip (125.3 KB)


(RemObjects) #4

Thanks, logged as bugs://78749 (for the init? thing)


(marc hoffman) #5

Ah, the problem with the filter() is not the call, but that you RETURN the result. your method is declared to return a [T], but filter() returns a sequence (this is a deliberate different between SBL and Apple’s implementation of filter, because (a) it’s the sensible thing to do and (b) whoever designs Apple’s Swift libraries does not understand how protocols and polymorphism should work and thus designs really shitty APIs. :wink:

you’ll either want to change the method to return an Sequence<T>, or call .ToList(), eg:

	return array.filter({ (o) -> Bool in  // <- error here
	if let o = o as? Filterable {
		return o.match(query: cleanQuery)
	} else {
		// if object isn't Filterable, always include it
		return true
		}
	}).ToList()

(on an unrelated note, you need parenthesis around the (o), thats a recent change in Swift (3 iirc) to force those. that, or just { o in ... }).


(RemObjects) #6

bugs://78749 got closed with status fixed.