1

What's needed to get this code running? Hi, I already have this part of code. It searches in an array of struct and delivers - if found - the index of that item:

    for index in 0 ..< gSteering.count {
        if gSteering[index].Ext == fileExtension.uppercaseString {
            priority = index
            break
        }
    }

I'm sure, that there is are shoreter and more elegant way in SWIFT using library functions. Any hints?

2 Answers 2

1

Something like

let priority = gSteering.indexOf() {
    $0.Ext == fileExtension.uppercaseString
}

P.S. And if you want priority to default to maxint in case if item is not found:

let priority = gSteering.indexOf() {
    $0.Ext == fileExtension.uppercaseString
} ?? Int.max
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I see that indexOf is only part of 2.0. I still use XCode 6.3.2. I think I will change when moving to 7.0.
In Swift 1.2 you can try using this: let priority = find(gSteering, fileExtension.uppercaseString) ?? Int.max
I get the error: '(C.Index?, Int)' is not convertable to 'Equatable' So I added: func ==(l: Steering, r: Steering) -> Bool { return l.Ext == r.Ext } But this doesn't make sense to me. :-( And of course it didn't work. Steering is the name of the struct type.
Sorry, I forgot about this .Ext thing. Can you try this: find(lazy(a).map({ $0.Ext }), fileExtension.uppercaseString) ?? Int.max
0

Here's one I could come up with:

if let index = (gSteering.map{ $0.Ext }).indexOf(fileExtension.uppercaseString) 
{ 
    priority = index
}
else 
{
    // Not found.
}

And here's another one:

let priority = gSteering.indexOf { $0.Ext == fileExtension.uppercaseString }

And here's one to get the object directly instead of the index:

// This will give you an array with all the results that match.
let priorityObj = gSteering.filter { $0.Ext == fileExtension.uppercaseString } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.