Struct Array Filter Problem

Hey guys, first i have to say i'm new to swift. I think it's easy for you to solve my problem, but i got stuck.

Here is the code:

.................................................................................................

struct box {
var ID = ""
var a = 0.0
var b = 0.0
var c = 0.0
var d = 0.0
}

var boxArray = [box] ()

var newBox = box()

print("Please enter ID: ", terminator: "")
newBox.ID = String(readLine()!)

let filteredArray = boxArray.filter{$0 == newBox.ID}
filteredArray.isEmpty ...

...................................................................................................

I want to make sure, that you can't enter an ID that is already used. Above is my attempt to code this, but just creates errors. How can I filter the boxArray only for String-type ?

This is the error:
Referencing operator function '==' on 'StringProtocol' requires that 'box' conform to 'StringProtocol'

Answered by Claude31 in 693479022

When you write:

$0 == newBox.ID

you try to equate a box ($0 is an item in boxArray, thus a box) to a String.

That cannot work.

So, you have to write:

let filteredArray = boxArray.filter{$0.ID == newBox.ID}
if filteredArray.isEmpty {
  // Then we can accept the entry
}

Note: a struct name should start with Uppercase: Box

This is probably your first post on the forum. Welcome.

Don't hesitate to ask more if it still doesn't work ; otherwise, don't forget to close the thread by marking the correct answer.

Accepted Answer

When you write:

$0 == newBox.ID

you try to equate a box ($0 is an item in boxArray, thus a box) to a String.

That cannot work.

So, you have to write:

let filteredArray = boxArray.filter{$0.ID == newBox.ID}
if filteredArray.isEmpty {
  // Then we can accept the entry
}

Note: a struct name should start with Uppercase: Box

This is probably your first post on the forum. Welcome.

Don't hesitate to ask more if it still doesn't work ; otherwise, don't forget to close the thread by marking the correct answer.

Thank you very much. Works well.

Struct Array Filter Problem
 
 
Q