Dictionary search the key and get the value - swift

I got a plist object which contains all the words key=english and value=malay and I assigned in to 2 different arrays which is english and malay. Now I want a textfield where I want to search the english word and print the malay word in the label.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
#IBOutlet weak var selectedLabel: UILabel!
#IBOutlet weak var searchText: UITextField!
#IBOutlet weak var wordTable: UITableView!
var english = [String]()
var malay = [String]()
var words: [String: String] = [:]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
wordTable.dataSource = self
wordTable.delegate = self
searchText.delegate = self
if let path = Bundle.main.path(forResource: "words", ofType: "plist"){
if let plistData = FileManager.default.contents(atPath: path){
do {
let plistObject = try PropertyListSerialization.propertyList(from: plistData, options: PropertyListSerialization.ReadOptions(), format: nil)
words = (plistObject as? [String: String])!
english = [String] (words.keys)
malay = [String] (words.values)
} catch {
print("Error Serialize")
}
} else {
print("Error reading data")
}
} else {
print("Property list")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return english.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell!
cell = tableView.dequeueReusableCell(withIdentifier: "tabelCell")
if cell == nil {
cell = UITableViewCell(
style: UITableViewCellStyle.value2,
reuseIdentifier: "tableCell")
print("creating a table cell")
}
cell!.textLabel!.text = english[indexPath.row]
cell!.detailTextLabel?.text = malay[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedLabel.text = malay[indexPath.row]
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard
textField.resignFirstResponder()
return true
}
#IBAction func searchBtn(_ sender: UIButton) {
let result = words.filter {$0.key == searchText.text}
if result.count > 0 {
print(result)
selectedLabel.text! = result.values //error
} else {
print("Not found")
}
}
}
the output I expecting is textfield(Bus) which is english word then in the label show me the malay word(Bas)

You have a plist file as a Dictionary. So you can get the dictionary object from the plist file and already answer here.
Make a structure for better data binding.
struct Word {
var english: String
var malay: String
}
Then declare an array of words globally in your ViewController.
var words: [Word] = [] // An empty array
In viewDidLoad: fetch data from plist file.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
wordTable.dataSource = self
wordTable.delegate = self
searchText.delegate = self
if let path = Bundle.main.path(forResource: "words", ofType: "plist") {
if let plistData = FileManager.default.contents(atPath: path){
do {
guard let plistObject = try PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as? [String: String] else {
// Plist is not [String: String]
return
}
// Here you need to change the code. Converting the dictionary into struct array
var words: [Word] = plistObject.map {Word(english: $0.key, malay: $0.value)}
/// Then sort by english word if needed
words.sorted {$0.english < $1.english}
} catch {
print("Error Serialize")
}
} else {
print("Error reading data")
}
} else {
print("Property list")
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return words.count
}
Update your cell data as well.
cell!.textLabel!.text = words[indexPath.row].english
cell!.detailTextLabel?.text = words[indexPath.row].malay
And your button action with minor modification:
#IBAction func searchBtn(_ sender: UIButton) {
let result = words.filter {$0.english == searchedText}
if let word = result.first {
selectedLabel.text = word.malay
} else {
selectedLabel.text = "" // No data found
}
}
You can replace $0.english == searchedText with {$0.english.contains(searchedText)} if you want to filter with contains, But in that case you might get the multiple result. I assume that in your case you need it as a translator so use ==.

Why don't you search in your plist object? I think it is simpler
#IBAction func searchBtn(_ sender: UIButton) {
guard let words = plistObject as? [String: String], let key = searchText.text else { return }
selectedLabel.text = words[key] ?? ""
}
Something like this.

Related

SearchBar doesn't returns results until activated and typing

I see empty rows when my tableView is loaded for the first time. But if I activate searchBar, write something into textField everything works correctly even i clean all the text. I want the app works without these extra steps. But I don't understand where exactly I am making the mistake.
class NextTableViewCell: UITableViewController, UISearchBarDelegate, UISearchControllerDelegate {
#IBOutlet weak var searchBar: UISearchBar!
var ref: DatabaseReference?
let db = Firestore.firestore()
var messages: [Message] = []
var filteredMessages: [Message] = []
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
tableView.dataSource = self
loadMessages()
filteredMessages = messages
}
Func loadMessages retrieves data from Firebase
func loadMessages() {
let user = Auth.auth().currentUser?.email
let docRef = db.collection(K.FStore.collectionName).document(user!)
docRef.addSnapshotListener { (querySnapshot, error) in
self.messages = []
if let e = error {
print(e)
} else {
if let snapshotDocuments = querySnapshot?.data(){
for item in snapshotDocuments {
if let key = item.key as? String, let translate = item.value as? String {
let newMessage = Message(key: key, value: translate)
self.messages.append(newMessage)
}
}
DispatchQueue.main.async { [self] in
self.messages.sort(by: {$1.key > $0.key})
self.tableView.reloadData()
}
}
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredMessages.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = filteredMessages[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ListVC", for: indexPath)
cell.textLabel?.text = message.key + " - " + message.value
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredMessages = []
if searchText == "" {
filteredMessages = messages
}else{
for item in messages {
if item.key.lowercased().contains(searchText.lowercased()){
if let key = item.key as? String, let translate = item.value as? String {
let newMessage = Message(key: key, value: translate)
self.filteredMessages.append(newMessage)
}
}
}
}
tableView.reloadData()
}
The problem is that filteredMessages is empty when the view controller loads and only gets populated when you search.
Since filteredMessages is essentially a subset of messages, you need to set filteredMessages to messages upon fetching them from the database.
Try adding a line that does that in your loadMessages() method:
DispatchQueue.main.async { [self] in
self.messages.sort(by: {$1.key > $0.key})
self.filteredMessages = self.messages // Add this line
self.tableView.reloadData()
}

How to display the list of data initially in View Controller

This is my Pokedex. It works per say... A minor issue I have with this is when you initially open the app, it doesn't show the list of data, just blank. When you enter something in search bar, it appears even when you delete everything and no letters in the search bar.
I looked for how to display the list initially and compared with a functional code but can't figure out what caused this.
Any helps and ideas will be appreciated.
Here is my main ViewController:
import UIKit
class ViewController: UITableViewController, UISearchBarDelegate {
#IBOutlet weak var searchBar: UISearchBar!
var pokemon: [Pokemon] = []
var filteredData: [Pokemon] = []
func capitalize (text: String) -> String {
function and followed by the remaining text without the first letter
return text.prefix(1).uppercased() + text.dropFirst()
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://pokeapi.co/api/v2/pokemon?limit=151")
guard let u = url else {
return
}
URLSession.shared.dataTask(with: u) { (data, reponse, error) in
guard let data = data else {
return
}
do {
let pokemonList = try JSONDecoder().decode(PokemonList.self, from: data)
self.pokemon = pokemonList.results
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch let error {
print("\(error)")
}
}.resume()
searchBar.delegate = self
filteredData = pokemon
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PokemonCell", for: indexPath)
cell.textLabel?.text = capitalize(text: filteredData[indexPath.row].name)
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "PokemonSegue" {
if let destination = segue.destination as? PokemonViewController {
destination.pokemon = filteredData[tableView.indexPathForSelectedRow!.row]
}
}
}
func searchBar (_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = []
if searchText == "" {
filteredData = pokemon
}
else {
for pokemon in pokemon {
if pokemon.name.lowercased().contains(searchText.lowercased()){
filteredData.append(pokemon)
}
}
}
self.tableView.reloadData()
}
}
this:
let pokemonList = try JSONDecoder().decode(PokemonList.self, from: data)
self.pokemon = pokemonList.results
DispatchQueue.main.async {
self.tableView.reloadData()
}
Happens asynchroniously after you receive the data and way after this
searchBar.delegate = self
filteredData = pokemon
is executed, you can put breakpoints and check for yourself.
You should assign pokemon to filteredData in the "do" statement
right before tableView.reloadData()
URLSession works asynchronously. Move the line
filteredData = pokemon
into the completion handler of the data task
do {
let pokemonList = try JSONDecoder().decode(PokemonList.self, from: data)
self.pokemon = pokemonList.results
self.filteredData = pokemonList.results
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch let error {
print("\(error)")
}
}.resume()
searchBar.delegate = self
}
And your function capitalize is redundant, String has a property capitalized
And this is a more efficient version of textDidChange
func searchBar (_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
filteredData = pokemon
} else {
filteredData = pokemon.filter { $0.name.range(of: searchText, options: .caseInsensitive) != nil }
}
self.tableView.reloadData()
}

Swift Error with (outlets, keyPath, key value and UITableViewCellContentView)

I'm new to swift and I was just working on this program that has a table view with a list of names that the user can search through. It was working fine, until I tried to implement a UISearchbar and it gave me the error
Failed to set (keyPath) user defined inspected property on (UITableViewCellContentView): [<UITableViewCellContentView 0x7fb4624048c0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key keyPath.
I've done some research and I'm figured out that this error normally occurs when there is a problem with IB Outlets, but my outlets seem to be doing fine and this is what they look like-
Photo of my Outlet Connections
If you think there might be a problem in my code- here it is (Sorry it is messy):
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
if searchBar.text == "" {
searchBar.placeholder = "Enter Name"
return true
} else {
return true
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching == true {
return searchingPeople.count
} else {
return people.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tblView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if searching == true {
cell.textLabel?.text = searchingPeople[indexPath.row]
} else {
cell.textLabel?.text = people[indexPath.row]
}
return cell
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchingPeople = people.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
searching = true
tblView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
view.endEditing(true)
searching = false
searchBar.text = ""
tblView.reloadData()
}
var people: [String] = []
var searchingPeople = [String()]
var searching = false
#IBOutlet weak var tblView: UITableView!
#IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
tblView.delegate = self
tblView.dataSource = self
searching = false
searchBar.text = ""
guard let path = Bundle.main.path(forResource: "finalDataPapa", ofType: "json") else { return }
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
// print(json)
guard let array = json as? [Any] else { return }
//38104 people
var i: Int = 1
while i < 38104 {
guard let personDict = array[i] as? [String: Any] else { return }
guard let personfName = personDict["FIRST NAME"] as? String else { print("Persons name in numbers"); return }
guard let personlName = personDict["LAST NAME"] as? String else { print("Persons name in numbers"); return }
//guard let personmName = personDict["MIDDLE"] as? String else { print("Persons name in numbers"); return }
let fullName = "\(personfName) \(personlName)"
people.append(fullName)
i = i + 1
}
DispatchQueue.main.async {
self.tblView.reloadData()
}
}
catch {
print(error)
}
class People: Decodable {
let LASTNAME: String?
let FIRSTNAME: String?
let MIDDLE: String?
enum CodingKeys: String, CodingKey {
case FIRSTNAME = "FIRST NAME"
case LASTNAME = "LAST NAME"
case MIDDLE = "MIDDLE"
}
}
}
}

search in retrieved data from json in swift3

I retrieve data from service URL in swift3 and displayed in tableview. I tried to search names, it shows filtered names but another cell is not updating. please check my below code.
class MyViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var searchBar: UISearchBar!
var filteredArray = [String]()
var shouldShowSearchResults = false
var nameArray = [String]()
var emailArray = [String]()
var tableData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
downloadData()
createSearchBar()
// Do any additional setup after loading the view.
}
func createSearchBar(){
searchBar.showsCancelButton = false
searchBar.placeholder = "Enter your search"
searchBar.delegate = self
self.navigationItem.titleView = searchBar
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
tableData = nameArray
if shouldShowSearchResults
{
return filteredArray.count
}
else
{
return tableData.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:mycell! = tableView.dequeueReusableCell(withIdentifier: "cell") as! mycell
if shouldShowSearchResults
{
cell.name.text = filteredArray[indexPath.row]
cell.email.text = emailArray[indexPath.row]
return cell
}
else
{
cell.name.text = tableData[indexPath.row]
cell.email.text = emailArray[indexPath.row]
return cell
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
searchBar.endEditing(true)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
shouldShowSearchResults = true
searchBar.endEditing(true)
self.tableView.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredArray = tableData.filter({
(names:String) -> Bool in
return names.lowercased().range(of: searchText.lowercased()) != nil
})
if searchText != ""
{
shouldShowSearchResults = true
self.tableView.reloadData()
}
else
{
shouldShowSearchResults = false
self.tableView.reloadData()
}
}
func downloadData()
{
let url = URL(string: "http://www.json-generator.com/api/json/get/crdvbKvLoy?indent=2")!
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 10000)
URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
return
}
do {
if let jsonData = try JSONSerialization.jsonObject(with:data!, options: []) as? [[String:AnyObject]] {
print(jsonData)
// Utility.SharedInstance.dict_UserDetails3 = jsonData as AnyObject
for item in jsonData {
if let name = item["Name"] as? AnyObject {
self.nameArray.append(name as! String)
}
if let email = item["Email"] as? AnyObject{
self.emailArray.append(email as! String)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
} catch let error as NSError {
print(error)
}
}.resume()
}
}
output:
search___________
Name Email
----------------
Wasim wasim#gmail.com
Dravid dravid#gmail.com
Kohli virat#gmail.com
Kallis Jaques#gmail.com
I entered in search text as K
-----------------------------
search_____K______
Name Email
----------------
Kohli wasim#gmail.com
Kallis dravid#gmail.com
In this search works, but Email field not updating. please check once. I am tried more samples but not solved. please check once, what changes I do to solve this problem.
you filter name array but not the email address array. so the indexes don't match up.
The best solution is to not separate related data. Structure it properly.
struct Person {
var name: String
var email: String
}
var people: [Person]?
var filteredResults: [Person]?
Using a struct for a person that holds the name and email together, you can filter this array easier and the data wont get out of sync.

How to access a property of a tableview cell from viewcontroller?

Please see screenshot. There is a repliesTableView, replyTextField and replyButtonin ViewController. repliesTableView cell is called ReplyCell. In ReplyCell there is a commentTableView to list all comments for that reply and a textfField, a commentButton to add new comments.
I have problem when add new replies and new comments. I guess I need to make comments array in ReplyCell empty when I click the Reply button. How can I make this happen? I have no idea how to access comments arrayfrom the root ViewController.
Exact problems: fter clicking commentButton, all comments in every cell doubled. After clicking replyButton, comments went to wrong cell.
Code:
import UIKit
import Firebase
class TopicForumVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet weak var topicNameLabel: UILabel!
#IBOutlet weak var replyNumberLabel: UILabel!
#IBOutlet weak var repliesTableView: UITableView!
#IBOutlet weak var replyTextField: UITextField!
var topicName:String?
var firstKey:String?
var secondKey:String?
var replies = [String]()
var replyButtonTapped = false
override func viewDidLoad() {
super.viewDidLoad()
repliesTableView.delegate = self
repliesTableView.dataSource = self
replyTextField.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
topicNameLabel.text = self.topicName
loadReplies()
}
func loadReplies() {
self.replies = []
DataService.ds.Categories_Base.child(self.firstKey!).child("Topics").observe(.value, with:{(snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
if let topicDict = snap.value as? Dictionary<String,AnyObject> {
if let topic = topicDict["text"] as? String {
if topic == self.topicName {
self.secondKey = snap.key
UserDefaults.standard.setValue(snap.key, forKey: Key_SecondKey)
if let replyDict = topicDict["replies"] as? Dictionary<String,AnyObject> {
for eachDict in replyDict {
if let textDict = eachDict.value as? Dictionary<String,AnyObject> {
if let reply = textDict["text"] as? String {
self.replies.append(reply)
self.replyNumberLabel.text = String(self.replies.count)
}
}
}
}
}
}
}
}
self.repliesTableView.reloadData()
}
})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return replies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ReplyCell") as? ReplyCell {
let reply = replies[indexPath.row]
cell.configureReplyCell(reply: reply)
return cell
} else {
return UITableViewCell()
}
}
#IBAction func replyButtonTapped(_ sender: Any) {
replyButtonTapped = true
if let reply = replyTextField.text, reply != "" {
self.replies = []
DataService.ds.Categories_Base.child(self.firstKey!).child("Topics").child(self.secondKey!).child("replies").childByAutoId().child("text").setValue(reply)
self.repliesTableView.reloadData()
let i = replies.count
for n in 0..<i {
let indexPath = IndexPath(row: n, section: 1)
let cell = repliesTableView.cellForRow(at: indexPath) as! ReplyCell
cell.comments = []
cell.repliesToReplyTableView.reloadData()
}
self.replyTextField.text = ""
self.replyButtonTapped = false
}
}
}
import UIKit
import Firebase
class ReplyCell: UITableViewCell,UITableViewDataSource,UITableViewDelegate, UITextFieldDelegate {
#IBOutlet weak var replyTextView: UITextView!
#IBOutlet weak var repliesToReplyTableView: UITableView!
#IBOutlet weak var commentTextField: UITextField!
var reply:String?
var comments = [String]()
var replyKey:String?
override func awakeFromNib() {
super.awakeFromNib()
self.comments = []
repliesToReplyTableView.delegate = self
repliesToReplyTableView.dataSource = self
commentTextField.delegate = self
loadComments()
}
func configureReplyCell(reply:String) {
self.reply = reply
self.replyTextView.text = self.reply
}
func loadComments() {
self.comments = []
if let firstKey = UserDefaults.standard.value(forKey: Key_FirstKey) as? String, let secondKey = UserDefaults.standard.value(forKey: Key_SecondKey) as? String {
DataService.ds.Categories_Base.child(firstKey).child("Topics").child(secondKey).child("replies").observe(.value, with:{(snapshot) in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
if let replyDict = snap.value as? Dictionary<String,AnyObject> {
if let reply = replyDict["text"] as? String {
if reply == self.reply {
self.replyKey = snap.key
DataService.ds.Categories_Base.child(firstKey).child("Topics").child(secondKey).child("replies").child(snap.key).child("comments").observe(.value, with: { (commentSnapshot) in
if let commentSnapshots = commentSnapshot.children.allObjects as? [FIRDataSnapshot] {
for commentSnap in commentSnapshots {
if let commentDict = commentSnap.value as? Dictionary<String,AnyObject> {
if let comment = commentDict["text"] as? String {
self.comments.append(comment)
}
}
}
}
self.repliesToReplyTableView.reloadData()
})
}
}
}
}
}
})
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let commentCell = tableView.dequeueReusableCell(withIdentifier:"CommentCell")
commentCell?.textLabel?.text = comments[indexPath.row]
return commentCell!
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
#IBAction func commentBtnPressed(_ sender: Any) {
if let comment = commentTextField.text, comment != "" {
self.comments = []
if let firstKey = UserDefaults.standard.value(forKey: Key_FirstKey) as? String, let secondKey = UserDefaults.standard.value(forKey: Key_SecondKey) as? String {
DataService.ds.Categories_Base.child(firstKey).child("Topics").child(secondKey).child("replies").child(self.replyKey!).child("comments").childByAutoId().child("text").setValue(comment)
if let myViewController = parentViewController as? TopicForumVC {
// myViewController.repliesTableView.reloadData()
myViewController.replies = []
}
self.repliesToReplyTableView.reloadData()
self.commentTextField.text = ""
self.replyKey = ""
}
}
}
I don't really know the exact circumstances of what you're building but there are two ideas that may offer some guidance.
1) If your table is displaying content from a data source then you will likely have some kind of reference. E.g. when loading the cells (in this case CustomCell) you'll do something like get the index of the cell and get the same index from the data, and put that data in the cells content. If that's the case, all you have to do on the button click is use tableview.cellForRowAtIndexPath with your sender object, and then remove the array from the data source, e.g. tableDataSource[index] = nil and reload the tableView.
2) If you have a stored property on the CustomCell that you've add specifically for storing this array, then you'd cast the sender object to CustomCell and remove the property, as in Kim's answer.
Hope this helps, but without more information it's kind of hard to tell.
let cell = tableview.cellForRowAtIndexPath(...) as? CustomCell
if cell != nil {
let arr = cell.array
}
BTW: I would re-think storing your array in the cell..