[英][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.我正在学习 swift 并且我正在尝试通过传递用户输入定义的名称字符串来初始化播放器 object 但我必须解开它并解开它会抛出错误。 It's an assignment so I don't think Im allowed to changed the parameter in Player to a String optional.这是一项任务,所以我认为我不允许将 Player 中的参数更改为可选的字符串。 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'目前得到一个'从 initiazlizer 返回而不初始化所有存储的属性'
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如果“str”为“nil”,则播放器未初始化
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.