0

For example:

var myArray = ["first string","second string"]

myArray.append(35) // Here will be an error
4
  • I think Apple has some nice documentation about this. developer.apple.com/library/ios/documentation/Swift/Conceptual/… Commented Jan 24, 2016 at 12:20
  • 1
    Your array is of type [String], with elements of type String. Hence, swift expects new members of the array to be, also, of type String, whereas 35 above is an integer literal. Try myArray.append("35") or myArray.append(String(35) ?? ""). Commented Jan 24, 2016 at 12:22
  • I`m just learning swift, and I want to know - is it possible to add number to array if it has type of STRING ? Commented Jan 24, 2016 at 12:27
  • Type the array to be more generic, [Any], I believe, and you can append 35. But this way you lose type information. Commented Jan 24, 2016 at 12:28

2 Answers 2

2

If you Option-click on myArray, you will see that it is of type [String] (array of String). You can only add Strings to myArray.

If you want to be able to add Int to your array, you will need a more inclusive type. If you make your array [Any], you can put anything in it.

var myArray:[Any] = ["first string","second string"]
myArray.append(35)   // This now works

If you want to store only Int and String, you can create your own custom protocol:

protocol StringsAndInts {
}

extension String: StringsAndInts {
}

extension Int: StringsAndInts {
}

var myArray:[StringsAndInts] = ["first string","second string"]

myArray.append(35)

print(myArray)  // ["first string", "second string", 35]

myArray.append(3.14)  // error: argument type 'Double' does not conform to expected type 'StringsAndInts'
Sign up to request clarification or add additional context in comments.

Comments

1

If you write

var myArray = ["first string","second string"]
print(myArray.dynamicType)

You will see that myArray is of type Array<String> or [String]. You cannot append an Int to that.

What you need to do is specify the type of the myArray yourself:

var myArray : [AnyObject] = ["first string","second string"]

print(myArray.dynamicType) // now prints Array<AnyObject> which you can add Int to

myArray.append(35)

3 Comments

Thanks! It is exactly what I1m looking for )
If you want to allow only Int and String in the array take a look at the answer by vacawama!
luk2302 please, note that this works only with help of free bridging, so import Foundation is necessary. String is bridged to _NSContiguousString and Int to __NSCFNumber.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.