how to pass data when i click the tableviewcell in swift4?












1















I want to send data from the tableview to the tableview of another ViewController. However, when pass the data, the data is converted to optional type.



So the SQL statement to be executed in another ViewController is not executed. An optional error occurred in ViewDidLoad.



I have also used the override prepare function, but the result is the same.
I can't understand why this is happening.



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

let itemCd = self.itemList[indexPath.row].itemCd
let itemName = self.itemList[indexPath.row].itemName

print(self.itemList[indexPath.row].itemCd)

let infoVC = self.storyboard?.instantiateViewController(withIdentifier: "HIST_RVC")
if let _infoVC = infoVC as? HistviewController {

_infoVC.itemCd = Int(itemCd)
_infoVC.itemName = String(itemName)

print(_infoVC.itemCd)
self.performSegue(withIdentifier: "moveHist", sender: self)
}


When I print, I get the following result,



first : 1,
second : Optional(1)


other viewController:



class HistviewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var itemCd: Int!
var itemName: String!
// SQLite DB
var infomationDAO = infoDAO()
var infoList: [InfoVO]!

override func viewDidLoad() {

self.infoList = self.infomationDAO.find(itemCd: self.itemCd)
self.tableview.reloadData()
}


sql find() function:



func find(itemCd: Int = 0) -> [InfoVO] {

var infoList = [InfoVO]()

do {
// define condition
let condition = itemCd == 0 ? "": "WHERE a.item_cd = (itemCd)"

let sql = """
select a.info_cd, a.info_name, b.item_name
from info_table a
join item_table b
on a.info_name = b.item_name
(condition)
order by a.item_cd ASC
"""

let rs = try self.fmdb.executeQuery(sql, values: nil)

while rs.next() {
...}









share|improve this question

























  • first : 1, second : Optional(1). Here itemCd -> 1 & Optional(1) and second -> first & second ryt ?

    – Vicky_Vignesh
    Nov 20 '18 at 5:00













  • @dinggu is your issue resolved?

    – iOS_Developer
    Nov 20 '18 at 10:59











  • this may help stackoverflow.com/questions/5210535/…

    – iOS_Developer
    Nov 20 '18 at 19:45













  • _infoVC.itemName = String(describing:itemName)

    – iOS_Developer
    Nov 20 '18 at 19:46
















1















I want to send data from the tableview to the tableview of another ViewController. However, when pass the data, the data is converted to optional type.



So the SQL statement to be executed in another ViewController is not executed. An optional error occurred in ViewDidLoad.



I have also used the override prepare function, but the result is the same.
I can't understand why this is happening.



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

let itemCd = self.itemList[indexPath.row].itemCd
let itemName = self.itemList[indexPath.row].itemName

print(self.itemList[indexPath.row].itemCd)

let infoVC = self.storyboard?.instantiateViewController(withIdentifier: "HIST_RVC")
if let _infoVC = infoVC as? HistviewController {

_infoVC.itemCd = Int(itemCd)
_infoVC.itemName = String(itemName)

print(_infoVC.itemCd)
self.performSegue(withIdentifier: "moveHist", sender: self)
}


When I print, I get the following result,



first : 1,
second : Optional(1)


other viewController:



class HistviewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var itemCd: Int!
var itemName: String!
// SQLite DB
var infomationDAO = infoDAO()
var infoList: [InfoVO]!

override func viewDidLoad() {

self.infoList = self.infomationDAO.find(itemCd: self.itemCd)
self.tableview.reloadData()
}


sql find() function:



func find(itemCd: Int = 0) -> [InfoVO] {

var infoList = [InfoVO]()

do {
// define condition
let condition = itemCd == 0 ? "": "WHERE a.item_cd = (itemCd)"

let sql = """
select a.info_cd, a.info_name, b.item_name
from info_table a
join item_table b
on a.info_name = b.item_name
(condition)
order by a.item_cd ASC
"""

let rs = try self.fmdb.executeQuery(sql, values: nil)

while rs.next() {
...}









share|improve this question

























  • first : 1, second : Optional(1). Here itemCd -> 1 & Optional(1) and second -> first & second ryt ?

    – Vicky_Vignesh
    Nov 20 '18 at 5:00













  • @dinggu is your issue resolved?

    – iOS_Developer
    Nov 20 '18 at 10:59











  • this may help stackoverflow.com/questions/5210535/…

    – iOS_Developer
    Nov 20 '18 at 19:45













  • _infoVC.itemName = String(describing:itemName)

    – iOS_Developer
    Nov 20 '18 at 19:46














1












1








1


1






I want to send data from the tableview to the tableview of another ViewController. However, when pass the data, the data is converted to optional type.



So the SQL statement to be executed in another ViewController is not executed. An optional error occurred in ViewDidLoad.



I have also used the override prepare function, but the result is the same.
I can't understand why this is happening.



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

let itemCd = self.itemList[indexPath.row].itemCd
let itemName = self.itemList[indexPath.row].itemName

print(self.itemList[indexPath.row].itemCd)

let infoVC = self.storyboard?.instantiateViewController(withIdentifier: "HIST_RVC")
if let _infoVC = infoVC as? HistviewController {

_infoVC.itemCd = Int(itemCd)
_infoVC.itemName = String(itemName)

print(_infoVC.itemCd)
self.performSegue(withIdentifier: "moveHist", sender: self)
}


When I print, I get the following result,



first : 1,
second : Optional(1)


other viewController:



class HistviewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var itemCd: Int!
var itemName: String!
// SQLite DB
var infomationDAO = infoDAO()
var infoList: [InfoVO]!

override func viewDidLoad() {

self.infoList = self.infomationDAO.find(itemCd: self.itemCd)
self.tableview.reloadData()
}


sql find() function:



func find(itemCd: Int = 0) -> [InfoVO] {

var infoList = [InfoVO]()

do {
// define condition
let condition = itemCd == 0 ? "": "WHERE a.item_cd = (itemCd)"

let sql = """
select a.info_cd, a.info_name, b.item_name
from info_table a
join item_table b
on a.info_name = b.item_name
(condition)
order by a.item_cd ASC
"""

let rs = try self.fmdb.executeQuery(sql, values: nil)

while rs.next() {
...}









share|improve this question
















I want to send data from the tableview to the tableview of another ViewController. However, when pass the data, the data is converted to optional type.



So the SQL statement to be executed in another ViewController is not executed. An optional error occurred in ViewDidLoad.



I have also used the override prepare function, but the result is the same.
I can't understand why this is happening.



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

let itemCd = self.itemList[indexPath.row].itemCd
let itemName = self.itemList[indexPath.row].itemName

print(self.itemList[indexPath.row].itemCd)

let infoVC = self.storyboard?.instantiateViewController(withIdentifier: "HIST_RVC")
if let _infoVC = infoVC as? HistviewController {

_infoVC.itemCd = Int(itemCd)
_infoVC.itemName = String(itemName)

print(_infoVC.itemCd)
self.performSegue(withIdentifier: "moveHist", sender: self)
}


When I print, I get the following result,



first : 1,
second : Optional(1)


other viewController:



class HistviewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var itemCd: Int!
var itemName: String!
// SQLite DB
var infomationDAO = infoDAO()
var infoList: [InfoVO]!

override func viewDidLoad() {

self.infoList = self.infomationDAO.find(itemCd: self.itemCd)
self.tableview.reloadData()
}


sql find() function:



func find(itemCd: Int = 0) -> [InfoVO] {

var infoList = [InfoVO]()

do {
// define condition
let condition = itemCd == 0 ? "": "WHERE a.item_cd = (itemCd)"

let sql = """
select a.info_cd, a.info_name, b.item_name
from info_table a
join item_table b
on a.info_name = b.item_name
(condition)
order by a.item_cd ASC
"""

let rs = try self.fmdb.executeQuery(sql, values: nil)

while rs.next() {
...}






ios swift xcode






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 6:39









Henri Normak

4,46021832




4,46021832










asked Nov 20 '18 at 4:32









dinggudinggu

526




526













  • first : 1, second : Optional(1). Here itemCd -> 1 & Optional(1) and second -> first & second ryt ?

    – Vicky_Vignesh
    Nov 20 '18 at 5:00













  • @dinggu is your issue resolved?

    – iOS_Developer
    Nov 20 '18 at 10:59











  • this may help stackoverflow.com/questions/5210535/…

    – iOS_Developer
    Nov 20 '18 at 19:45













  • _infoVC.itemName = String(describing:itemName)

    – iOS_Developer
    Nov 20 '18 at 19:46



















  • first : 1, second : Optional(1). Here itemCd -> 1 & Optional(1) and second -> first & second ryt ?

    – Vicky_Vignesh
    Nov 20 '18 at 5:00













  • @dinggu is your issue resolved?

    – iOS_Developer
    Nov 20 '18 at 10:59











  • this may help stackoverflow.com/questions/5210535/…

    – iOS_Developer
    Nov 20 '18 at 19:45













  • _infoVC.itemName = String(describing:itemName)

    – iOS_Developer
    Nov 20 '18 at 19:46

















first : 1, second : Optional(1). Here itemCd -> 1 & Optional(1) and second -> first & second ryt ?

– Vicky_Vignesh
Nov 20 '18 at 5:00







first : 1, second : Optional(1). Here itemCd -> 1 & Optional(1) and second -> first & second ryt ?

– Vicky_Vignesh
Nov 20 '18 at 5:00















@dinggu is your issue resolved?

– iOS_Developer
Nov 20 '18 at 10:59





@dinggu is your issue resolved?

– iOS_Developer
Nov 20 '18 at 10:59













this may help stackoverflow.com/questions/5210535/…

– iOS_Developer
Nov 20 '18 at 19:45







this may help stackoverflow.com/questions/5210535/…

– iOS_Developer
Nov 20 '18 at 19:45















_infoVC.itemName = String(describing:itemName)

– iOS_Developer
Nov 20 '18 at 19:46





_infoVC.itemName = String(describing:itemName)

– iOS_Developer
Nov 20 '18 at 19:46












3 Answers
3






active

oldest

votes


















1














As per your code your performing segue so you need to implement func prepare(for segue: UIStoryboardSegue, sender: Any?) in your controller and pass the value.



Code:



 var selectedIndex = 0
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let controller = segue.destination as? HistviewController {
let itemCd = self.itemList[selectedIndex].itemCd
let itemName = self.itemList[selectedIndex].itemName
controller.itemcd = Int(itemcd)
controller.itemName = String(itemName)
}
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedIndex = indexPath.row
}





share|improve this answer































    0
















    1. In HistviewController declare itemCd and itemName as non-optional. There are only a very few cases where it's useful to declare primitive types like String and Int as optional.



      var itemCd = 0
      var itemName = ""



    2. The init?(String) initializer return an optional because "abc" cannot be represented by an Int. Use the nil-coalescing operator to pass 0 if the initializer fails:



      _infoVC.itemCd = Int(itemCd) ?? 0





    Note: In Swift avoid variable names with starting underscore character. That's very objective-c-ish. Write



    if let infoVC = self.storyboard?.instantiateViewController(withIdentifier: "HIST_RVC") as? HistviewController {





    share|improve this answer































      -2














      instead of _infoVC.itemCd = Int(itemCd) this use
      guard let item = Int(itemCd){
      return
      }
      _infoVC.itemCd = item



      or



      _infoVC.itemCd = Int(itemCd)!






      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386281%2fhow-to-pass-data-when-i-click-the-tableviewcell-in-swift4%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        As per your code your performing segue so you need to implement func prepare(for segue: UIStoryboardSegue, sender: Any?) in your controller and pass the value.



        Code:



         var selectedIndex = 0
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let controller = segue.destination as? HistviewController {
        let itemCd = self.itemList[selectedIndex].itemCd
        let itemName = self.itemList[selectedIndex].itemName
        controller.itemcd = Int(itemcd)
        controller.itemName = String(itemName)
        }
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectedIndex = indexPath.row
        }





        share|improve this answer




























          1














          As per your code your performing segue so you need to implement func prepare(for segue: UIStoryboardSegue, sender: Any?) in your controller and pass the value.



          Code:



           var selectedIndex = 0
          override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          if let controller = segue.destination as? HistviewController {
          let itemCd = self.itemList[selectedIndex].itemCd
          let itemName = self.itemList[selectedIndex].itemName
          controller.itemcd = Int(itemcd)
          controller.itemName = String(itemName)
          }
          }

          func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
          self.selectedIndex = indexPath.row
          }





          share|improve this answer


























            1












            1








            1







            As per your code your performing segue so you need to implement func prepare(for segue: UIStoryboardSegue, sender: Any?) in your controller and pass the value.



            Code:



             var selectedIndex = 0
            override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let controller = segue.destination as? HistviewController {
            let itemCd = self.itemList[selectedIndex].itemCd
            let itemName = self.itemList[selectedIndex].itemName
            controller.itemcd = Int(itemcd)
            controller.itemName = String(itemName)
            }
            }

            func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            self.selectedIndex = indexPath.row
            }





            share|improve this answer













            As per your code your performing segue so you need to implement func prepare(for segue: UIStoryboardSegue, sender: Any?) in your controller and pass the value.



            Code:



             var selectedIndex = 0
            override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let controller = segue.destination as? HistviewController {
            let itemCd = self.itemList[selectedIndex].itemCd
            let itemName = self.itemList[selectedIndex].itemName
            controller.itemcd = Int(itemcd)
            controller.itemName = String(itemName)
            }
            }

            func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            self.selectedIndex = indexPath.row
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 20 '18 at 5:45









            iOS_MaccusiOS_Maccus

            30610




            30610

























                0
















                1. In HistviewController declare itemCd and itemName as non-optional. There are only a very few cases where it's useful to declare primitive types like String and Int as optional.



                  var itemCd = 0
                  var itemName = ""



                2. The init?(String) initializer return an optional because "abc" cannot be represented by an Int. Use the nil-coalescing operator to pass 0 if the initializer fails:



                  _infoVC.itemCd = Int(itemCd) ?? 0





                Note: In Swift avoid variable names with starting underscore character. That's very objective-c-ish. Write



                if let infoVC = self.storyboard?.instantiateViewController(withIdentifier: "HIST_RVC") as? HistviewController {





                share|improve this answer




























                  0
















                  1. In HistviewController declare itemCd and itemName as non-optional. There are only a very few cases where it's useful to declare primitive types like String and Int as optional.



                    var itemCd = 0
                    var itemName = ""



                  2. The init?(String) initializer return an optional because "abc" cannot be represented by an Int. Use the nil-coalescing operator to pass 0 if the initializer fails:



                    _infoVC.itemCd = Int(itemCd) ?? 0





                  Note: In Swift avoid variable names with starting underscore character. That's very objective-c-ish. Write



                  if let infoVC = self.storyboard?.instantiateViewController(withIdentifier: "HIST_RVC") as? HistviewController {





                  share|improve this answer


























                    0












                    0








                    0









                    1. In HistviewController declare itemCd and itemName as non-optional. There are only a very few cases where it's useful to declare primitive types like String and Int as optional.



                      var itemCd = 0
                      var itemName = ""



                    2. The init?(String) initializer return an optional because "abc" cannot be represented by an Int. Use the nil-coalescing operator to pass 0 if the initializer fails:



                      _infoVC.itemCd = Int(itemCd) ?? 0





                    Note: In Swift avoid variable names with starting underscore character. That's very objective-c-ish. Write



                    if let infoVC = self.storyboard?.instantiateViewController(withIdentifier: "HIST_RVC") as? HistviewController {





                    share|improve this answer















                    1. In HistviewController declare itemCd and itemName as non-optional. There are only a very few cases where it's useful to declare primitive types like String and Int as optional.



                      var itemCd = 0
                      var itemName = ""



                    2. The init?(String) initializer return an optional because "abc" cannot be represented by an Int. Use the nil-coalescing operator to pass 0 if the initializer fails:



                      _infoVC.itemCd = Int(itemCd) ?? 0





                    Note: In Swift avoid variable names with starting underscore character. That's very objective-c-ish. Write



                    if let infoVC = self.storyboard?.instantiateViewController(withIdentifier: "HIST_RVC") as? HistviewController {






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 20 '18 at 9:32









                    vadianvadian

                    148k14159178




                    148k14159178























                        -2














                        instead of _infoVC.itemCd = Int(itemCd) this use
                        guard let item = Int(itemCd){
                        return
                        }
                        _infoVC.itemCd = item



                        or



                        _infoVC.itemCd = Int(itemCd)!






                        share|improve this answer






























                          -2














                          instead of _infoVC.itemCd = Int(itemCd) this use
                          guard let item = Int(itemCd){
                          return
                          }
                          _infoVC.itemCd = item



                          or



                          _infoVC.itemCd = Int(itemCd)!






                          share|improve this answer




























                            -2












                            -2








                            -2







                            instead of _infoVC.itemCd = Int(itemCd) this use
                            guard let item = Int(itemCd){
                            return
                            }
                            _infoVC.itemCd = item



                            or



                            _infoVC.itemCd = Int(itemCd)!






                            share|improve this answer















                            instead of _infoVC.itemCd = Int(itemCd) this use
                            guard let item = Int(itemCd){
                            return
                            }
                            _infoVC.itemCd = item



                            or



                            _infoVC.itemCd = Int(itemCd)!







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 20 '18 at 9:38

























                            answered Nov 20 '18 at 9:14









                            Manish_NainwalManish_Nainwal

                            372




                            372






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386281%2fhow-to-pass-data-when-i-click-the-tableviewcell-in-swift4%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                How to change which sound is reproduced for terminal bell?

                                Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                                Can I use Tabulator js library in my java Spring + Thymeleaf project?