Amy Ritchie
Amy Ritchie

Reputation: 21

How to define var outside if statement and use it outside

var firstname: [String] = []
var year = Int.random(in: 1900 ... 2020)
if (1900 ..< 1910).contains(year){
    if (gender == "male"){
        firstname = _1900s_boysnames_uk.randomElement()
    }
}

Get error cannot assign value of type 'String?' to type '[String]' for firstname How do i fix this?

Upvotes: 0

Views: 75

Answers (2)

user9500574
user9500574

Reputation: 152

You got this error, because the array _1900s_boysnames_uk might be empty, so the returned value from the randomElement() also might be nil, for that we consider the returned value as optional

you can add ? int your first line, which means that the array can contain nil values, but it's not the better way

var firstname: [String?] = []

or you can use this syntax inside your if condition

if let firstname = _1900s_boysnames_uk.randomElement() {
    firstname.append(firstname)
}

Addition, please

var firstname: [String] = []

It means that the variable "firstname" will contain a list of names

and to to add a new name to the list, you will use "append" like:

firstname.append(_1900s_boysnames_uk.randomElement())

If you want to assign only a name to it, use:

var firstname: String

the recommendation in Swift is to use a camel case naming convention when naming variables. If you’re not aware of camel case, it is a naming convention that uses a lowercase letter for the first word in a variable name followed by a capital letter for each subsequent word.

Upvotes: 0

Vasilis D.
Vasilis D.

Reputation: 1456

firstname variable is a type on [String] whitch means that is should contain an array of Strings.

On line firstname = _1900s_boysnames_uk.randomElement() you assign a value of String to the array of Strings.

To fix it you can change the line into firstname.append(_1900s_boysnames_uk.randomElement()).

Upvotes: 6

Related Questions