简体   繁体   中英

[Swift]How do I initialize a class expecting a String with a ReadLine?

I'm learning swift and I'm trying to initialize a Player object by passing it name String defined by user input but I have to unwrap it and unwrapping it throws and error. It's an assignment so I don't think Im allowed to changed the parameter in Player to a String optional. Is there a way to make this work? If so how?

class PlayGame{
private var player:Player

public init(){
   
print("Welcome, please enter your name: ")
    if let str = readLine()
    {
        self.player = Player(name:str)
    }
}

} Currently getting a 'Return from initiazlizer without initializing all stored properties'

class Player{
private var name:String

public init(name:String)
{
    self.name = name
}

this is what I'm trying and its failing

here

public init(){

    print("Welcome, please enter your name: ")
    if let str = readLine()
    {
        self.player = Player(name:str)
    }
}

If "str" is "nil" then the player is not initialized

I did fix it

public init(){
    print("Welcome, please enter your name: ")
    if let str = readLine()
    {
        self.player = Player(name:str)
    } else {
        player = Player(name:"default")
    }
}

I can use "nil coalescing operator" (also called "default operator").

class PlayGame {
    private var player: Player

    public init() {
        print("Welcome, please enter your name: ")
        let str = readLine() ?? "unnamed"
        self.player = Player(name: str)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM