Search code examples
swiftruntime-errordowncast

Why I am getting swift Dynamic Cast failed?


This line of code seems to be causing the problem

{
gymnastTables.gymnastsArray = defualts.objectForKey("Gymnasts") as Array
}

Why I am getting a downcast error?


Solution

  • objectForKey has return type: AnyObject? therefore it might be nil

    You can first unwrap it by as AnyObject! and after downcast to Array

    gymnastTables.gymnastsArray = 
            defualts.objectForKey("Gymnasts") as AnyObject! as Array<AnyObject>
    

    You didn't mention Array type so I added AnyObject that will be always true