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
Take Screenshot of Host App Using iOS Share/Action Extensions
Dyld: Library Not Loaded, App Requires Afnetworking 2.0.0 But Provides Version 1.0.0
Swiftui on MACos - Handle Single-Click and Double-Click at the Same Time
How to Make Prepareforsegue with Uicollectionview
Swiftui: How to Set Position of Scrollview to Top Left? (Both Scrolls Is Enabled)
Realitykit - How to Add a Video Material to a Modelentity
Why Does Somestruct() Is Anyobject Return True
How to Make Uicollectionview Reload Once It Receives Data from Firebase
Enum's Rawvalue Property Not Recognized
Convert String to Nsdate in Swift
What's the Rationale of Swift's Size Methods Taking 'Int'S
Swiftui Behavior of .Frame(Height: Nil)
Correct Way to Use Nwconnection for Long-Running Tcp Socket
Why I Can Not Use Equatable Function in My View When the View Can Use It in Swiftui
How to "Explicitly" Implement a Protocol in Swift? If It Is Impossible, Why
Why Upload Alamofire Background Request Don't Executes in Background