0

I was trying out Swift arrays in the Playground, when I noticed this peculiar behaviour

The below code works fine.

import UIKit

var array = [1,2,3,"Booyaa"]

But, as soon as I remove the "import UIKit" line from the Playground, I get the following error

Playground execution failed: /var/folders/tx/tvyf1r314wj9371f491qx8wjbqbgsr/T/./lldb/11708/playground71.swift:2:17: error: 'Int' is not convertible to 'IntegerLiteralConvertible' var array = [1, 2, 3, "Booyaa"]

Why does this happen?

kkaosninja
  • 1,301
  • 11
  • 21

2 Answers2

1

The correct answer is here, in response to an identical question I posted on the Apple Dev forums => https://forums.developer.apple.com/message/35389

It's because Swift Arrays can only contain objects that are the same type. Your array has integers and a string. When you import UIKit the objects in the array become objects of type NSObject by virtue of Swift's inference engine. To see for yourself, add the line after the array definition, you'll see the type as Swift.array

import UIKit  
var array = [1,2,3,"Swift2"]  
array.dynamicType 
kkaosninja
  • 1,301
  • 11
  • 21
0

With high programming language this need a lexical structure for checking and compare complex type as your question. And it's implemented in Foundation framework.

Also UIKit implemented some UI api as UIView, etc... And in UIKit framework it's need using Foundation framework.

BTW: Foundation framework is core Swift, Objective-C language.

Hope this helps!

Long Pham
  • 7,464
  • 3
  • 29
  • 40