Cannot set optional value, prints nil

Viewed 77

I am working on project that writes to google sheets. I am trying to Unmerge cells. This function works however it unmerges everything in the sheet. This is because it is not setting the .range value. When I print (as seen below) the "test" value all range values are shown accordingly however when I print the "request.unmergeCells?.range" it says nil. I am further confused as I use this exact code elsewhere for a merge command and it loads the values fine (see second snippet of code.)

I have tried for days to resolve this issue with no avail. Any thoughts?

func unmergecell1() {

            let request = GTLRSheets_Request.init()

            let test = GTLRSheets_GridRange.init()

            rowstart = 4
            rowend = 100
            columnstart = 0
            columnend = 100

            test.startRowIndex = rowstart
            test.endRowIndex = rowend
            test.startColumnIndex = columnstart
            test.endColumnIndex = columnend

            request.unmergeCells?.range = test

            request.unmergeCells = GTLRSheets_UnmergeCellsRequest.init()

            print("=========unmerge==============")
            print(test)
            print(request.unmergeCells?.range)

            let batchUpdate = GTLRSheets_BatchUpdateSpreadsheetRequest.init()

            batchUpdate.requests = [request]


            let createQuery = GTLRSheetsQuery_SpreadsheetsBatchUpdate.query(withObject: batchUpdate, spreadsheetId: spreadsheetId)


        service.executeQuery(createQuery) { (ticket, result, NSError) in

               }
              }
func mergecell() {

        let request = GTLRSheets_Request.init()

        request.mergeCells = GTLRSheets_MergeCellsRequest.init()

        let test = GTLRSheets_GridRange.init()

        test.startRowIndex = rowstart
        test.endRowIndex = rowend
        test.startColumnIndex = columnstart
        test.endColumnIndex = columnend
        request.mergeCells?.range = test

        request.mergeCells?.mergeType = kGTLRSheets_MergeCellsRequest_MergeType_MergeRows

        let batchUpdate = GTLRSheets_BatchUpdateSpreadsheetRequest.init()
        batchUpdate.requests = [request]

        let createQuery = GTLRSheetsQuery_SpreadsheetsBatchUpdate.query(withObject: batchUpdate, spreadsheetId: spreadsheetId)

        service.executeQuery(createQuery) { (ticket, result, NSError) in

        }
       }
1 Answers

I think you need to switch these 2 lines:

request.unmergeCells?.range = test

request.unmergeCells = GTLRSheets_UnmergeCellsRequest.init()

The 2nd line initates the unmerge request, and only after you initate it can you add the range to it. So by making it the other way round, as below, it should work.

request.unmergeCells = GTLRSheets_UnmergeCellsRequest.init()
request.unmergeCells?.range = test
Related