4

Why am i getting this error? Error: Value of type 'Any' (aka protocol<>) has no member 'name'

import UIKit
var alican = (name: "alican", surame:"yilmaz")
var array:[Any] = [alican]
print(array[0].name)
L'lynn
  • 167
  • 1
  • 13

3 Answers3

6

You've declared your Array as containing Any type. If you declare it like this the error should go away:

var array:[(name: String, surame: String)] = [alican]

If the array needs to be able to contain Any type you can pull out just those matching a particular type using flatMap.

var array:[Any] = [alican]
var nameSurnames = array.flatMap({ return $0 as? (name: String, surame: String) })
print(nameSurnames[0].name)
Casey Fleser
  • 5,707
  • 1
  • 32
  • 43
  • OK i understand that i need to decleare the type of array explicitly. But what if my tuple's members are dynamic. For example i want an array that takes in tuples but the tuples will come in may have three four or five or any member number and they do not have tags like "name" "surname". – L'lynn Jun 02 '16 at 09:42
  • @AlicanYilmaz in that case a tuple is probably not what you want but a struct with optional properties. Always avoid heterogeneous collections where possible. – Fogmeister Jun 02 '16 at 09:47
  • Expanded my answer to account for the situation you described. – Casey Fleser Jun 02 '16 at 09:48
  • OK thanks. It may not safe as you say @Fogmeister. But i was a dream that adding random tuples which are have random members in to append in an array. But it is not conventional and safe that i undestood. So if i force to use dynamic collections, maybe like nosql structure. What i need to use in swift. If i want to have a class with properties that are unknown to be initialized in constructor, maybe. – L'lynn Jun 02 '16 at 09:56
1

Just drop the typing of the array...

var array = [alican]

Typs is inferred wherever possible by swift.

You only need to explicitly type a variable if it is not possible to infer it automatically.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
1

This is how you can access name and surname

var alican = (name: "alican", surame:"yilmaz")
var array = [alican]
print(array[0].name)
Umair Afzal
  • 4,947
  • 5
  • 25
  • 50