Swift: The Use of AnyObject and Any

Feedback


Solution 1:

Once a variable is declared, it cannot be altered. Therefore, it is necessary to create a new variable. One way to achieve this is by securely mapping

Any

items to

String

using

flatMap

.

var oldArray: [Any] = []
var newArray: [String] = oldArray.flatMap { String($0) }


Solution 2:

Updated to Swift 5

var arrayOfAny: [Any] = []
var arrayOfStrings: [String] = arrayOfAny.compactMap { String(describing: $0) }


Solution 3:


Utilize this syntactic sugar grammar, which allows for a concise one-liner of code.

var arr: [Any] = []
var strs = [String]()
arr = strs.map {$0 as! [String]}

Frequently Asked Questions

Posted in Ios