0

I have made a table with tableCell which contain Student information. Details of students are displayed in cells. The function below displays student information based on which cell is clicked.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let selectedRow = feedItems[indexPath.row]
    print(selectedRow)

}

On click of a cell gives the following output:

  ID: Optional("101"), Name: Optional("Neha Mahendrabhai Ghala"),Std: Optional("13"), School Name: Optional("N.k. College of commerce arts and mgmt. Malad")

I want to extract the "101" next to the ID and put in a string variable. How can I go about this?

  • let idString = "\\(feedItems[indexPath.row].ID!)" – Retterdesdialogs Dec 04 '18 at 10:11
  • What is the type of `selectedRow` (or `feedItems`)? Add it to the question. – user28434'mstep Dec 04 '18 at 10:11
  • `let selectedRow`, that's a `feedItem` right? Also, what did you do in `cellForAt:`? How did you extract data from `feedItems` to display it? Use the same mechanism. – Larme Dec 04 '18 at 10:13
  • 2
    Unrelated but consider to use less optionals. I can't imagine that there is any student without a `name` and `id`. And please conform to the naming convention that variable names start with a lowercase letter. – vadian Dec 04 '18 at 10:13
  • please read that ->[link] (https://stackoverflow.com/questions/53606860/updating-to-xcode-10-made-value-wrapped-with-optional/53607948#53607948) – TalBenAsulo Dec 04 '18 at 12:01

5 Answers5

1

you are getting Optional("101") becuase ID is declared as optional in the structure used. To use any optional value, you must first unwrap it. Unwrap it like as follows :

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedRow = feedItems[indexPath.row]
    print(selectedRow.ID ?? 0) //0 or -1 as per want it to be
    print(selectedRow.name ?? "")
}

or better use if let (optional binding)

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedRow = feedItems[indexPath.row]
    if let id = selectedRow.ID {
        print(id)
    }

    if let name = selectedRow.name {
        print(name)
    }
}

SideNote - ID and name should not be declared as optionals because there will never be a student without ID and name

Also I would recommend to read Optionals SO post once to know more about Optional in swift

Rizwan
  • 3,324
  • 3
  • 17
  • 38
0

The selectedRow have type of your Student so you can extract this with selectedRow.ID. But since you have this variable as Optional you may want to unwrap this.

ChooGoo
  • 85
  • 8
0
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let selectedItem = feedItems[indexPath.row] {
      if let id = selectedItem.id {
       print(id)
      }
    }
   }
  1. it is bad practice to name variable as ID
  2. Use selectedItem since selectedRow signifies a row.
  3. Unwrap optionals use either if or guard. Here I am using if
user28434'mstep
  • 6,290
  • 2
  • 20
  • 35
prex
  • 719
  • 4
  • 17
0

The value is wrapped you just have to unwrap it by using Exclamation Mark or providing default value.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
debugPrint(feedItems[indexPath.row].id ?? "");

}

gn. Dolly
  • 76
  • 4
-1

Use this method to get String:

You can paste this method in String's extension to use globally.

static func getString(_ message: Any?) -> String {
    guard let strMessage = message as? String else {
        guard let doubleValue = message as? Double else {
            guard let intValue = message as? Int else {
                guard let int64Value = message as? Int64 else {
                    return ""
                }
                return String(int64Value)
            }
            return String(intValue)
        }

        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = 0
        formatter.maximumFractionDigits = 2
        formatter.minimumIntegerDigits = 1
        guard let formattedNumber = formatter.string(from: NSNumber(value: doubleValue)) else {
            return ""
        }
        return formattedNumber
    }
    return strMessage.trimWhiteSpaceAndNewLine()
}
nitin.agam
  • 1,949
  • 1
  • 17
  • 24
  • 1
    Why? Why a bunch of unnecessary and expensive runtime checks if you **do** know the actual type? – vadian Dec 04 '18 at 10:26
  • I have created this method to use for multi-purpose. You can get a string from an Int, Float, Double or even for any invalid string object. If you will pass an invalid string object then it will return an empty string. This method helps me a lot. – nitin.agam Dec 04 '18 at 10:30