Swift无法在方法中分配给self [英] Swift Cannot assign to self in a method

查看:123
本文介绍了Swift无法在方法中分配给self的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到了一个奇怪的问题

I've just faced a strange problem

我有一个叫做Letter

class Letter
{    
    init() {}
}

我对此课程有一个扩展:

And I have an extension for this class:

extension Letter
{
    convenience init(file_path:String) { self = Letter.loadFromFile(file_path)}
    class func loadFromFile(file_path:String)->Letter {...}
}

我需要创建并初始化文件路径,当我调用Letter(file_path)时,我需要一个由func loadFromFile返回的新对象.如何分配init方法或返回新对象?

I need to create and init with path to file and when i call Letter(file_path) I need a new object that returned by a func loadFromFile. How to assign in an init method or to return a new object?

//编辑 同样的问题...

//Edit The same problem...

推荐答案

返回该类实例的类函数在Swift中似乎是一种反模式.您会注意到,像[NSString stringWithString:@"some other string"]这样的带有" Objective-C类方法使转换成为了缺少"的便捷初始化程序:NSString(string: "some other string").

Class functions that return instances of that class seems to be an anti-pattern in Swift. You'll notice that the "with" Objective-C class methods like [NSString stringWithString:@"some other string"] made the transition as "with"-less convenience initializers: NSString(string: "some other string").

此外,您还需要另外,由于您1)定义了原始类,2)不需要便捷构造器的作用域与指定的构造器不同,所以我看不出有任何理由将其放置在扩展中.

Also, since you're 1) defining the original class and 2) don't need the convenience initializer scoped differently than the designated initializer, I don't see any reason to place it in an extension.

将它们放在一起:

class Letter {
    init() { … }

    convenience init(filePath: String) {
        self.init()
        loadFromFile(filePath)
    }

    func loadFromFile(filePath: String) { … }
}

let letter1 = Letter()
letter1.loadFromFile("path1")

let letter2 = Letter(filePath: "path2")

总而言之,在Swift中分配给self的类比就是调用一个初始化器.

In summary, the analogy for assigning to self in Swift is calling an initializer.

让我知道这是否对您有用!

Let me know if this works for you!

这篇关于Swift无法在方法中分配给self的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆