Last active
May 23, 2016 20:08
-
-
Save brentsimmons/08e1e68a4defe2abca644d74106d1f31 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import Cocoa | |
var str = "Hello, playground" | |
protocol Message: class { | |
var uniqueID: String {get} | |
} | |
class LocalMessage: Message { | |
let uniqueID = NSUUID().UUIDString | |
} | |
var messages = [Message]() | |
let oneMessage = LocalMessage() | |
let secondMessage = LocalMessage() | |
messages += [oneMessage, secondMessage] as [Message] // The cast seems superfluous, but I can live with it. | |
// Scenario: | |
// | |
// A Message is updated via data from the web. | |
// I want to redisplay the corresponding row in a table view. | |
// To do so, I need the index of that row. | |
// I get the index of the row by getting the index of that Message in an array of Message. | |
// | |
// I don't actually care if the comparison uses pointer equality or ==. For my case it amounts to the same thing. | |
// These all fail to compile: | |
//let indexOfMessage = messages.indexOf(oneMessage) //cannot convert value of type 'LocalMessage' to expected argument type '@noescape (Message) throws -> Bool' | |
// | |
//let indexOfMessage = messages.indexOf(oneMessage as Message) //cannot convert value of type 'Message' to expected argument type '@noescape (Message) throws -> Bool' | |
// | |
//let indexOfMessage = (messages as NSArray).indexOfObjectIdenticalTo(oneMessage) //'[Message]' is not convertible to 'NSArray' | |
// I can make it work this way, using pointer equality (which is fine). | |
// | |
// Is there a better way to solve this problem, with performance that is not worse? | |
// (For instance, filter wouldn’t stop when it found the Message, but the for-loop does stop upon finding it.) | |
var indexOfMessage = 0 | |
var found = false | |
for oneMessage in messages { | |
if oneMessage === oneMessage { | |
found = true | |
break | |
} | |
indexOfMessage++ | |
} | |
if found { | |
print(indexOfMessage) | |
} | |
// Update — the answer comes via Twitter: | |
// https://twitter.com/bzamayo/status/734803341956485120 | |
let indexOfMessage = messages.indexOf { $0 === oneMessage } | |
print(indexOfMessage) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This seems to work fine.