0

I have an arrays

var searchArray = [(
    ean: String,
    name: String,
    weight: String,
    brand: String,
    percent: String,
    inside: String,
    img: String,
    packet: String,
    date: String)
    ]()

var searchArrayFiltered = [(
    ean: String,
    name: String,
    weight: String,
    brand: String,
    percent: String,
    inside: String,
    img: String,
    packet: String,
    date: String)
    ]()

I have a code for search from arrays and show result in table:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchArrayFiltered = searchText.isEmpty ? searchArray : searchArray.filter({(dataString: String) -> Bool in
        return dataString.(of: searchText, options: .caseInsensitive) != nil
    })

    tableView.reloadData()
}

But in line return dataString.String(of: searchText, options: .caseInsensitive) != nil i have an error:

Value of tuple type '(ean: String, name: String, weight: String, brand: String, percent: String, inside: String, img: String, packet: String, date: String)' has no member 'String'

If I change dataString.String to dataString.name, I have an error:

Cannot call value of non-function type 'String'

Please help me to do search from searchArray for "name".

0

2 Answers 2

3

First of all you are discouraged from using a tuple as array type. Use a custom struct or class

Apple says:

Tuples are useful for temporary groups of related values. They’re not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple.


There are two major issues:

  1. Copy&Paste mistake, you mean dataString.range(of...
  2. dataString is not a string, it's a tuple (the type annotation is redundant)

Change the function to

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchArrayFiltered = searchText.isEmpty ? searchArray : searchArray.filter({tuple -> Bool in
        return tuple.name.range(of: searchText, options: .caseInsensitive) != nil
    })

    tableView.reloadData()
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I'm always working with java\android, and swift for me is Hell.
0

create a struct for

struct Model {
    var ean: String
    var name: String
    var weight: String
    var brand: String
    var percent: String
    var inside: String
    var img: String
    var packet: String
    var date: String
}

then apply filter on your [Model]

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.