tdm3732
tdm3732

Reputation: 57

strange error, returned value type different from the one in function body

I have XlsxReaderWritter Framework added to my app. I am having trouble with the first steps of using this framework, which is getting a worksheet in an excel file

Here is my code:

let file = BRAOfficeDocumentPackage.open(syllabusFileURL.relativePath)! 
inputFile = file.workbook.worksheets[0] //this line does not compile and gives me this "Type [Any]! has no subscript members"

Alright so I cast it as the following:

inputFile = file.workbook.worksheets[0] as! BRAWorksheet

Now it compiles but I get a runtime error saying:

Could not cast value of type 'BRAWorksheet' (0x10df5fdc0) to 'BRAWorksheet' (0x10ce8e430).

So it seems the value is already BRAWorksheet and does not need casting, but as I said it wont compile saying its of type [Any]!

In the official documentation, here is how they get a worksheet;

#####Swift

//First worksheet in the workbook
var firstWorksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0]

//Worksheet named "Foo"
var fooWorksheet: BRAWorksheet = spreadsheet.workbook.createWorksheetNamed("Foo")

Since it is an imported framework, I checked the original Objective-C file for the function. It does not seem to return [Any]!. Here is the body:

- (NSArray *)worksheets {
    NSMutableArray *worksheets = @[].mutableCopy;

    for (BRASheet *sheet in _sheets) {
        BRAWorksheet *worksheet = [self.relationships relationshipWithId:sheet.identifier];
        worksheet.styles = _styles;
        worksheet.sharedStrings = _sharedStrings;
        worksheet.calcChain = _calcChain;
        [worksheets addObject:worksheet];
    }

    return worksheets.count ? worksheets : nil;
}

So can Anyone tell me what the duck is going on??!

Upvotes: 0

Views: 136

Answers (2)

pansora abhay
pansora abhay

Reputation: 912

If You are using swift 3

let path: String = Bundle.main.path(forResource: "demo", ofType: "xlsx")!
let spreadsheet: BRAOfficeDocumentPackage = BRAOfficeDocumentPackage.open(path)
let worksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0] as! BRAWorksheet
let sheet: BRASheet = spreadsheet.workbook.sheets[0] as! BRASheet
print(sheet.name) // print "Sheet1"

Upvotes: 2

clemens
clemens

Reputation: 17721

You should take care of the optional result:

var firstWorksheet: BRAWorksheet? = spreadsheet.workbook.worksheets?[0]

Upvotes: 0

Related Questions