I am using a tableView to show text only. Inside cell, I am using a UITextView with dynamic height and linkDetection with html text converted to attributedString.
I am parsing the html text to attributed text inside my model class below way:
if let nodeValue = dict["blurb_link"]{
blurb_link = nodeValue as? String
let attrString = NSMutableAttributedString(attributedString: (blurb_link?.html2AttributedString)!)
atr_blurb_link = attrString
}
html2AttributedString in an extension of String which returns an attributedString from html text.
I am populating my cell inside cell subclass via below way,
textViewBlurbLink.attributedText = model.atr_blurb_link
But the problem that is happening is, whenever a new cell is loaded, the tableview stucks for a fraction of second which make the tableView scrolling a bit jerky and disturbing to user.
There are no images, no videos no heavy task inside cell which can cause a jerky scroll. Please tell me what could be possible reason of this jerky and hiccup scrolling?
EDIT:
The layout of my cell is:
After getting response I have populated tableView below way:
TSNetworkManager.getDataFor(Request: dataRequest, success: {response in
//print(response.responseObject!)
let model = TSLatestModel.init(WithDictionary: response.responseObject as? [String : Any])
completion(model)
tblLatest.reloadData()
}, failure: {error in
onError(error)
})
and inside cellForRowAtIndexPath
let modelLatestDetails = model?.data![indexPath.section].items![indexPath.row]
cell.setupCellData(model: modelLatestDetails!)
Inside the setupCellData in tableViewCell subclass I am setting the text into textView.
EDIT2:
This the total codebase of my model class
class TSLatestModel: TSModelBase {
var data : [LatestListModel]?
override init(WithDictionary dictionary: [String : Any]?) {
super.init(WithDictionary: dictionary)
if let dict = dictionary{
if let nodeValue = dict["data"] {
data = [LatestListModel]()
for latest in nodeValue as! [Any]{
let model = LatestListModel.init(WithDictionary: latest as? [String:Any])
data?.append(model)
}
}
}
}
}
class LatestListModel: NSObject {
var storyname : String?
var main_title : String?
var color : String?
var issuedate : String?
var formatted_issue_date : String?
var id : String?
var cat_name : String?
var cat_id : String?
var order : Int?
var items : [TSLatestDetailsModel]?
var itemsModified : [TSLatestDetailsModel]?
init(WithDictionary dictionary: [String : Any]?) {
super.init()
if let dict = dictionary {
if let nodeValue = dict["items"] {
items = [TSLatestDetailsModel]()
itemsModified = [TSLatestDetailsModel]()
for item in nodeValue as! [Any] {
let model = TSLatestDetailsModel.init(WithDictionary: item as? [String : Any])
items?.append(model)
if !((item as! [String : Any])["one_liner"] as! String).isEmpty {
let filteredArray = itemsModified?.filter({$0.one_liner == ((item as! [String : Any])["one_liner"] as! String)})
if filteredArray?.count == 0 {
let model = TSLatestDetailsModel.init(WithDictionary: item as? [String : Any])
itemsModified?.append(model)
}
}
}
}
if let nodeValue = dict["item_list"] {
items = [TSLatestDetailsModel]()
itemsModified = [TSLatestDetailsModel]()
for item in nodeValue as! [Any] {
let model = TSLatestDetailsModel.init(WithDictionary: item as? [String : Any])
items?.append(model)
if !((item as! [String : Any])["one_liner"] as! String).isEmpty {
let filteredArray = itemsModified?.filter({$0.one_liner == ((item as! [String : Any])["one_liner"] as! String)})
if filteredArray?.count == 0 {
let model = TSLatestDetailsModel.init(WithDictionary: item as? [String : Any])
itemsModified?.append(model)
}
}
}
}
if let nodeValue = dict["_id"] {
storyname = nodeValue as? String
}
if let nodeValue = dict["order"] {
order = nodeValue as? Int
}
if let nodeValue = dict["category"] {
cat_id = (nodeValue as! [Any])[0] as? String
}
if let dictStoryType = dict["_id"] as? [String : Any] {
if let nodeValue = dictStoryType["issuedate"] {
issuedate = nodeValue as? String
}
if let nodeValue = dictStoryType["formated_issue_date_title"] {
formatted_issue_date = nodeValue as? String
}
if let nodeValue = dictStoryType["id"] {
id = nodeValue as? String
}
if let nodeValue = dictStoryType["category_name"] {
cat_name = nodeValue as? String
}
}
if let nodeValue = dict["name"] {
storyname = nodeValue as? String
}
if let nodeValue = dict["story"] {
storyname = nodeValue as? String
}
if let nodeValue = dict["main_title"] {
main_title = nodeValue as? String
}
if let nodeValue = dict["color"] {
color = nodeValue as? String
}
}
}
}
class TSLatestDetailsModel: NSObject {
var __v : Int?
var _id : String?
var title : String?
var topic_key : String?
var blurb : String?
var blurb_link : String?
var atr_blurb_link : NSMutableAttributedString?
var formated_issue_date : String?
var formated_issue_date_item : String?
var formated_issue_date_title : String?
var issue_link : String?
var issue_title : String?
var issue_date : String?
var one_liner : String?
var main_title : String?
var source : String?
var source_link : String?
var isActive : Bool?
var isDeleted : Bool?
var isfavourite : Bool?
var story_order_number : Int?
var story_type : String?
var categories : [String]?
var story_type_model : TSStoryTypeDetailsModel?
var favourite_category_id : String?
init(WithDictionary dictionary: [String : Any]?) {
super.init()
if let dict = dictionary{
if let nodeValue = dict["__v"]{
__v = nodeValue as? Int
}
if let nodeValue = dict["_id"]{
_id = nodeValue as? String
}
if let nodeValue = dict["title"]{
title = nodeValue as? String
}
if let nodeValue = dict["topic_key"]{
topic_key = nodeValue as? String
}
if let nodeValue = dict["blurb"]{
blurb = nodeValue as? String
}
if let nodeValue = dict["blurb_link"]{
blurb_link = nodeValue as? String
let attrString = NSMutableAttributedString(attributedString: (blurb_link?.html2AttributedString)!)
atr_blurb_link = attrString
}
if let nodeValue = dict["formated_issue_date"]{
formated_issue_date = nodeValue as? String
}
if let nodeValue = dict["issue_date"]{
issue_date = nodeValue as? String
}
if let nodeValue = dict["issue_link"]{
issue_link = nodeValue as? String
}
if let nodeValue = dict["issue_title"]{
issue_title = nodeValue as? String
}
if let nodeValue = dict["one_liner"]{
one_liner = nodeValue as? String
}
if let nodeValue = dict["main_title"]{
main_title = nodeValue as? String
}
if let nodeValue = dict["source"]{
source = nodeValue as? String
}
if let nodeValue = dict["source_link"]{
source_link = nodeValue as? String
}
if let nodeValue = dict["isActive"]{
isActive = nodeValue as? Bool
}
if let nodeValue = dict["isfavourite"]{
isfavourite = nodeValue as? Bool
}
if let nodeValue = dict["story_order_number"]{
story_order_number = nodeValue as? Int
}
if let nodeValue = dict["story_type"]{
story_type = nodeValue as? String
}
if let nodeValue = dict["formated_issue_date_title"]{
formated_issue_date_title = nodeValue as? String
}
if let nodeValue = dict["formated_issue_date_item"]{
formated_issue_date_item = nodeValue as? String
}
if let nodeValue = dict["favourite_category_ids"] {
if (nodeValue as! [String]).count > 0 {
favourite_category_id = (nodeValue as! [String])[0]
}
}
if let nodeValue = dict["story_type"] {
let model = TSStoryTypeDetailsModel.init(WithDictionary: nodeValue as? [String : Any])
story_type_model = model
}
if let nodeValue = dict["category"] {
categories = [String]()
for category in nodeValue as! [String] {
categories?.append(category)
}
}
}
}
}
The cellForRowAtIndexPath:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TSArchiveDetailsCell") as! TSArchiveDetailsCell
cell.delegate = self
if !((favoriteDetilsModel?.data![indexPath.section].items![indexPath.row].source!.isEmpty)!) {
cell.viewFav.isHidden = false
} else {
if favoriteDetilsModel?.data![indexPath.section].storyname?.lowercased() == "brush up" {
cell.viewFav.isHidden = false
} else {
cell.viewFav.isHidden = true
}
}
if isSayItOnRounds {
let modelLatestDetails = favoriteDetilsModel?.data![indexPath.section].items?.filter({$0._id! == selectedItemId})[0]
cell.setupCellData(model: modelLatestDetails!)
} else if isBrushUp {
let thirdBrushUpItemModel = favoriteDetilsModel?.data![indexPath.section].items![2]
if thirdBrushUpItemModel?._id == selectedItemId {
let modelLatestDetails = favoriteDetilsModel?.data![indexPath.section].items?.filter({$0._id == selectedItemId})
cell.setupCellData(model: modelLatestDetails![0])
} else {
let modelLatestDetails = favoriteDetilsModel?.data![indexPath.section].items![indexPath.row]
cell.setupCellData(model: modelLatestDetails!)
}
} else {
let modelLatestDetails = favoriteDetilsModel?.data![indexPath.section].items![indexPath.row]
cell.setupCellData(model: modelLatestDetails!)
}
return cell
}
Possible problems:
Cell layout. I need to see, how do you make layout and reuse cell.
Parsing data and drawing cells at the same time.
You need to create all data before (tableView.datasource = self or tableView.reloadData()). So, your [AttributedString] must be ready before reloading tableView. Do not parse data in cellfoRowAtIndexPath.
Also, check that tableView call cellfoRowAtIndexPath only one time for each cell during cell lifetime.
Related
I am trying to get data from firebase and use it as a model that I created.
Here is my model;
class UserData{
var nickname : String = ""
var onesignal_player_id : String = ""
var step_count : Int = 0
var total_point : Int = 0
var competitions : [String:Competition] = [String:Competition]()
}
class Competition{
var end_date : String = ""
var gift : String = ""
var id: String = ""
var name: String = ""
var users : [String:Int] = [:]
}
and this is my function;
func getFirebaseData() {
ref = Database.database().reference()
ref.child("users").child("HXXNCXf6RRS4WVO12shZ3j15BnG3").observe(.value) { (snapshot) in
if let snapshotValue = snapshot.value as? Dictionary<String,Any> {
//change userData with the snapshotValue
self.userData.nickname = snapshotValue["nickname"] as! String
self.userData.step_count = snapshotValue["step_count"] as! Int
self.userData.total_point = snapshotValue["total_point"] as! Int
self.userData.onesignal_player_id = snapshotValue["onesignal_player_id"] as! String
self.userData.competitions = snapshotValue["competitions"] as! [String:Competition]
//reload UI with userData
print(self.userData.competitions)
} else {
print("An error occured while assigning snapshotValue to userData")
}
}
}
This code gave me error like this;
Could not cast value of type '__NSDictionaryM' (0x1f47ada20) to 'StepCounterApp.Competition' (0x1004c06f0).
2021-01-02 23:05:49.985711+0300 StepCounterApp[32511:3685645] Could not cast value of type '__NSDictionaryM' (0x1f47ada20) to 'StepCounterApp.Competition' (0x1004c06f0).
but when i comment out the line included self.userData.competitions from getFirebaseData function, everything works fine.
What should I do? How can I use firebase data as a model?
Finally here is my firebase data;
The problem is in your data model. Declare your model data like this
class UserData {
var nickname : String = ""
var onesignal_player_id : String = ""
var step_count : Int = 0
var total_point : Int = 0
var competitions : Competition = Competition()
}
class Competition{
var end_date : String = ""
var gift : String = ""
var id: String = ""
var name: String = ""
var users : [String:Int] = [:]
init() {
}
init(with dictionary: [String: Any]) {
self.end_date = dictionary["end_date"] as! String
self.gift = dictionary["gift"] as! String
self.id = dictionary["id"] as! String
self.name = dictionary["name"] as! String
self.users = dictionary["users"] as! [String:Int]
}
}
And inside the getFirebaseData funcation
self.userData.competitions = Competition(with: snapshotValue["competitions"] as! [String: Any])
The problem was in my data model and with the help of Raja Kishan's data model sugestion I fixed the problem.
First I changed the model little bit;
class UserData{
var nickname : String = ""
var onesignal_player_id : String = ""
var step_count : Int = 0
var total_point : Int = 0
var competitions : [String:Competition] = [String:Competition]()
}
class Competition{
var end_date : String = ""
var gift : String = ""
var id: Int = 0
var name: String = ""
var users : [String:Int] = [:]
init() {
}
init(with dictionary: [String: Any]) {
self.end_date = dictionary["end_date"] as! String
self.gift = dictionary["gift"] as! String
self.id = dictionary["id"] as! Int
self.name = dictionary["name"] as! String
self.users = dictionary["users"] as! [String:Int]
}
}
Than I add a childSnapshot to my method so I can work directly the "competitions";
func getFirebaseData() {
ref = Database.database().reference()
ref.child("users").child("HXXNCXf6RRS4WVO12shZ3j15BnG3").observe(.value) { [self] (snapshot) in
if let snapshotValue = snapshot.value as? [String:Any] {
//change userData with the snapshotValue
self.userData.nickname = snapshotValue["nickname"] as! String
self.userData.step_count = snapshotValue["step_count"] as! Int
self.userData.total_point = snapshotValue["total_point"] as! Int
self.userData.onesignal_player_id = snapshotValue["onesignal_player_id"] as! String
//******
//This part of the coded added for to solve the problem starting from here
let childSnap = snapshot.childSnapshot(forPath: "competitions")
if let childSnapValue = childSnap.value as? [String:Any] {
childSnapValue.forEach { (element) in
self.userData.competitions.updateValue(Competition(with: element.value as! [String:Any]), forKey: element.key)
}
} else {
print("something wrong with the childSnap")
}
//to here
//******
} else {
print("An error occured while assigning snapshotValue to userData")
}
}
}
How can I clear the shared dictionary on logout in which I am saving login response?
Here is the code I am doing on getting status 1.
if(status == 1)
{
DispatchQueue.main.async {
GAReusableClass.sharedInstance.hideActivityIndicator()
UserDefaults.standard.set(self.DataDict, forKey:MaindataKey)
let Dict = self.mainDict[KData] as! [String: AnyObject]
print("self.DataDict", self.DataDict)
let User_ID = Dict[KUuid]as! String
print(User_ID)
let HMACSECRETKEY = self.deviceToken + "+" + User_ID
kHMACKey = HMACSECRETKEY
let cipher:String = CryptoHelper.encrypt(input:HMACSECRETKEY)!;
print(HMACSECRETKEY)
UserDefaults.standard.setValue(cipher, forKey:HmacKey)
UserDefaults.standard.set(true, forKey: "isLogin")
GAloginUserInfo.shared.saveUserInfo(dict: Dict )
let tabar = self.storyboard?.instantiateViewController(withIdentifier: "GAtHomeTabbarViewController") as! GAtHomeTabbarViewController
self.navigationController?.pushViewController(tabar, animated: true)
}
Here is the shared dictionary which I am using to save the values of login response.
import UIKit
import Firebase
class GAloginUserInfo: NSObject {
var loginUserMobileNo : String?
var loginUserId : String?
var loginUserUuid : String?
var loginUserCountry : String?
var loginUserCountryCode : String?
var loginUserEmail : String?
var loginUserlatitude : String?
var loginUserLongitude : String?
var loginUserName : String?
var loginUserQrcode : String?
var loginUserProfilePic : String?
var isverify : String?
var loginPassword : String?
var dateOfBirth: String?
var earnedPoints:String?
var loginUserGender:String?
var loginUserFollowers:Int = 0
static let shared = GAloginUserInfo()
func saveUserInfo (dict : [String : AnyObject?] ) {
if let loginUserMobileNo = dict["mobile"] as? String {
self.loginUserMobileNo = loginUserMobileNo
}
if let loginUserId = dict["id"] as? String {
self.loginUserId = loginUserId
}
if let loginUserUuid = dict["uuid"] as? String {
self.loginUserUuid = loginUserUuid
print(loginUserUuid)
}
if let loginUserCountry = dict["country"] as? String {
self.loginUserCountry = loginUserCountry
}
if let loginUserCountryCode = dict["country_code"] as? String {
self.loginUserCountryCode = loginUserCountryCode
}
if let loginUserEmail = dict["email"] as? String {
self.loginUserEmail = loginUserEmail
}
if let loginUserProfilePic = dict["profile_pic"] as? String {
self.loginUserProfilePic = loginUserProfilePic
}
if let loginUserLongitude = dict["logitude"] as? String {
self.loginUserLongitude = loginUserLongitude
}
if let loginUserName = dict["name"] as? String {
self.loginUserName = loginUserName
}
if let loginUserQrcode = dict["qr_code"] as? String {
self.loginUserQrcode = loginUserQrcode
}
if let Password = dict["password"] as? String{
self.loginPassword = Password
}
if let dateOfBirth = dict["dob"] as? String{
self.dateOfBirth = dateOfBirth
}
if let earnedPoints = dict["points"] as? String{
let myDouble = Double(earnedPoints)
let doubleStr = String(format: "%.2f", myDouble!)
self.earnedPoints = doubleStr
}
if let loginUserGender = dict["gender"] as? String{
self.loginUserGender = loginUserGender
}
if let loginUserFollowers = dict["followersCount"] as? Int{
self.loginUserFollowers = loginUserFollowers
}
}
}
Actually, the problem is when I log out and log in again with some other user it still shows some values of the previous user. I am clearing the userdefaults on the logout function. but I don't know how to clear this type of shared dictionary.
Use removeObject(forKey:)
to remove the values stored from user defaults in Logout method
UserDefaults.standard.removeObject(forKey: MaindataKey)
UserDefaults.standard.removeObject(forKey: HmacKey)
UserDefaults.standard.set(false, forKey: "isLogin")
Create a method to remove the values from the singleton class like this
extension GAloginUserInfo {
func removeUserInfo() {
self.loginUserMobileNo = nil
self.loginUserId = nil
self.loginUserUuid = nil
self.loginUserCountry = nil
self.loginUserCountryCode = nil
self.loginUserEmail = nil
self.loginUserlatitude = nil
self.loginUserLongitude = nil
self.loginUserName = nil
self.loginUserQrcode = nil
self.loginUserProfilePic = nil
self.isverify = nil
self.loginPassword = nil
self.dateOfBirth = nil
self.earnedPoints = nil
self.loginUserGender = nil
self.loginUserFollowers = 0
}
}
and call this method in logout
GAloginUserInfo.shared.removeUserInfo()
How can I get the data that in Struct model in new viewController
I got a viewController when i print the var in Struct model it appeare just fine.
I created New viewController trying to get the same data in otherview of that struct model but when i print it it give me nil
I tryied to make the model equal to the new model in the new viewController
MessageController View
var messages = [Message]()
var users = [Contact]()
var messagesDicionary = [String: Message]()
var testMSG : Message?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let message = self.messages[indexPath.row]
let chatPartnerId = message.chatPartnerId()
let ref = Database.database().reference().child("users").child(chatPartnerId)
ref.observe(.value) { (snap) in
if let dictinoary = snap.value as? [String: AnyObject] {
guard let email = dictinoary["email"] ,let profileimage = dictinoary["profileimage"], let userid = dictinoary["userid"], let username = dictinoary["username"] else {
return
}
var user = Contact()
user.userid = chatPartnerId
user.userid = chatPartnerId
let userValue = Contact.init(email: email as? String, username: username as? String, profileimage: profileimage as? String, userid: userid as? String)
self.users.append(userValue)
self.showChatControllerToUser(user: userValue)
print(message.receivername)
}
}
}
result of Print Optional("Omar")
ChatMessagesController View
var user :Contact?
var users = [Contact]()
var message: Message?
var messagesArray = [Message]()
func observeChatMessages() {
guard let uid = Auth.auth().currentUser?.uid else {
return
}
let userMessagesRef = Database.database().reference().child("usersmesssages").child(uid)
userMessagesRef.observe(.childAdded) { (snap) in
let messageId = snap.key
let messageRef = Database.database().reference().child("messages").child(messageId)
messageRef.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String:AnyObject] else {
return
}
let text = dictionary["text"] as? String
let receiverid = dictionary["receiverid"] as? String
let senderid = dictionary["senderid"] as? String
let time = dictionary["timestamp"] as? TimeInterval
let senderName = dictionary["sendername"] as? String
let receiverName = dictionary["receivername"] as? String
self.messagesArray.append(MessageValue)
self.chatTableView.reloadData()
print(self.message?.receivername)
})
}
}
result of print NIL
Message Model
struct Message {
var text: String?
var receiverid: String?
var senderid: String?
var timestamp: TimeInterval?
var sendername: String?
var receivername: String?
func chatPartnerId() -> String {
return (senderid == Auth.auth().currentUser?.uid ? receiverid : senderid)!
}
}
I tried to make in MessagesController
let chatMessage = ChatMessageController()
chatMessage.message = self.testMSG
I have a list of JSON data downloaded from server:
(DataModal.swift)
class DataModal {
var orderAutoid: Int?
var orderId: String?
var orderName: String?
var orderQty: String?
var orderStatus: String?
init(bOrder_autoid: Int, bOrder_id: String, bOrder_name: String, bOrder_qty: String, bOrder_status: String){
self.orderAutoid = bOrder_autoid
self.orderId = bOrder_id
self.orderName = bOrder_name
self.orderQty = bOrder_qty
self.orderStatus = bOrder_status
}
(OrderStructureDownloadProtocol.swift)
protocol OrderStructureDownloadProtocol: class {
func newItemDownload(items: Array<Any>)
}
....
var jsonElement = Dictionary<String, Any>()
var newOrders = Array<Any>()
for i in 0..<jsonResult.count {
jsonElement = jsonResult[i] as! Dictionary
let newOrder_autoid = jsonElement["orderAutoid"] as? Int ?? 0
let newOrder_id = jsonElement["orderId"] as? String ?? ""
let newOrder_name = jsonElement["orderName"] as? String ?? ""
let newOrder_qty = jsonElement["orderQty"] as? String ?? ""
let newOrder_status = jsonElement["orderStatus"] as? String ?? ""
let newOrder = BMSDataModal(bOrder_autoid: newOrder_autoid, bOrder_id: newOrder_id, bOrder_name: newOrder_name, bOrder_qty: newOrder_qty, bOrder_status: newOrder_status)
newOrders.append(newOrder)
}
DispatchQueue.main.async (
execute: { () -> Void in
self.delegate.newItemDownload(items: newOrders as! Array<Any>)
})
(tableview.swift)
var newOrdersArray = [BMSDataModal]()
func newItemDownload(items: Array<Any>) {
newOrdersArray = items as! [BMSDataModal]
newOrderLookupTableView.reloadData()
}
(tableview.swift another part)
let cell = tableView.dequeueReusableCell(withIdentifier: "orderLookupCell", for: indexPath) as! NewOrderTableViewCell
let item = newOrdersArray[indexPath.row]
cell.newHMNumber?.text = item.orderId ?? "-"
cell.newMP?.text = item.orderName ?? "-"
cell.newQTY?.text = item.orderQty ?? "-"
return cell
}
having all the old NS-style changed. The app is running okay, there are some items that need to reset. As my data-source always contain Double, but I declared it as a String, as I won't deal with calculation so I treated it as 'String'.
This is the var var types: [String]? and here i get this error myLabel3.text = place.types how can i adjust it? I looked to other similar questions but not find something that is the same to my problem.
import UIKit
import CoreLocation
private let geometryKey = "geometry"
private let locationKey = "location"
private let latitudeKey = "lat"
private let longitudeKey = "lng"
private let nameKey = "name"
private let openingHoursKey = "opening_hours"
private let openNowKey = "open_now"
private let vicinityKey = "vicinity"
private let typesKey = "types"
private let photosKey = "photos"
class QPlace: NSObject {
var location: CLLocationCoordinate2D?
var name: String?
var photos: [QPhoto]?
var vicinity: String?
var isOpen: Bool?
var types: [String]?
init(placeInfo:[String: Any]) {
// coordinates
if let g = placeInfo[geometryKey] as? [String:Any] {
if let l = g[locationKey] as? [String:Double] {
if let lat = l[latitudeKey], let lng = l[longitudeKey] {
location = CLLocationCoordinate2D.init(latitude: lat, longitude: lng)
}
}
}
// name
name = placeInfo[nameKey] as? String
// opening hours
if let oh = placeInfo[openingHoursKey] as? [String:Any] {
if let on = oh[openNowKey] as? Bool {
isOpen = on
}
}
// vicinity
vicinity = placeInfo[vicinityKey] as? String
// types
types = placeInfo[typesKey] as? [String]
// photos
photos = [QPhoto]()
if let ps = placeInfo[photosKey] as? [[String:Any]] {
for p in ps {
photos?.append(QPhoto.init(photoInfo: p))
}
}
}
this is place class and this is the func of my customTableViewCell where i want to add it
func update(place:QPlace) {
myLabel.text = place.getDescription()
myImage.image = nil
myLabel2.text = place.vicinity
myLabel3.text = place.types
var types: [String]? is an optional array of String; the value of myLabel3.text is an optional String, or String?.
You need to get a value out from the array or join the values in order to set your label text, eg:
myLabel3.text = place.types?.joined()