Get Compiler Error in Swift Indexof()

get compiler error in swift indexOf()

To use indexOf method with element as input param, your element type of dataSets which is IChartDataSet must conform to Equatable protocol as you can see from CollectionType extension definition:

    extension CollectionType where Generator.Element : Equatable {
/// Returns the first index where `value` appears in `self` or `nil` if
/// `value` is not found.
///
/// - Complexity: O(`self.count`).
@warn_unused_result
public func indexOf(element: Self.Generator.Element) -> Self.Index?
}

Or you can use predicate closure instead:

let localdataSetIndex = chartData!.dataSets.indexOf { $0 === globalSet }

indexOf using with arrays in Swift

class Message {
var id: Int
init(id: Int) {
self.id = id
}
}

var arr: [Message] = []
arr.append(Message(id: 1))
arr.append(Message(id: 2))
arr.append(Message(id: 3))
print(arr.indexOf { $0.id == 2 }) // Optional(1)

check the declaration !!

.indexOf(predicate: (Message) throws -> Bool)

How can I use array.indexOf with a protocol?

To be able to use indexOf in a protocol, it has to be Equatable. Conform your protocol to it and you'll be able to use it. For more info, take a look here.

Why do I get an error when attempting to invoke indexOf on a generic ArraySlice?

The compiler is giving you a confusing error message here—it isn't actually concerned about the argument. The return value is the source of the problem, since you aren't returning a value of type T, but an index of the array. You just need to change your return type to Int?:

func secondIndexOf<T: Equatable>(item: T, inArray array: Array<T>) -> Int? {
if let firstIndex: Int = array.indexOf(item) {
let slice: ArraySlice<T> = array.suffixFrom(firstIndex + 1)
return slice.indexOf(item)
}
return nil
}

index (of: element) does not exist

TaskItem needs to conform to the Equatable protocol in order to use index(of:).



Related Topics



Leave a reply



Submit