无法通过下标分配给Swift字符串

fjaof16o  于 2023-02-03  发布在  Swift
关注(0)|答案(3)|浏览(186)

我有一个类,它包含一个名称、一个图像、名称的虚线形式和名称的长度。例如,我可以有“狗”、一个狗的图像、“---"和名称长度3。
我只想为每个对象设置名称和图片,并自动设置dashNamenameLength

class Answer {
    var name = "name"
    var image: UIImage?
    var dashName = "name"
    var nameLength = 0

    init(){

        var a = 0
        nameLength = name.characters.count

        while a <= nameLength {
            if (name[a] == " ") {dashName[a] = " "}
            else {dashName[a] = "-"}
            a += 1
        }
    }
}

问题是这样的错误:““无法通过下标赋值:subscript is get-only”和另一个错误,显示:“下标不可用:不能为字符串添加Int下标”

a6b3iqyw

a6b3iqyw1#

因为String的下标运算符是get-only,所以请改用map方法,如下所示:

class Answer {
    var name = "name"
    var image: UIImage?
    var dashName = "name"
    var nameLength = 0
    
    init(){
        dashName = String(name.map {$0 == " " ? " " : "-"})
    }
}
tjjdgumg

tjjdgumg2#

和之前的mentioned一样,Swift的String类是其他语言所称的StringBuilder类,出于性能原因,Swift提供按索引设置字符;如果您不关心性能,一个简单的解决方案可能是:

public static func replace(_ string: String, at index: Int, with value: String) {
    let start = string.index(string.startIndex, offsetBy: index)
    let end = string.index(start, offsetBy: 1)
    string.replaceSubrange(start..<end, with: value)
}

或作为扩展名:

extension String {
    public func charAt(_ index: Int) -> Character {
        return self[self.index(self.startIndex, offsetBy: index)];
    }

    public mutating func setCharAt(_ index: Int, _ new: Character) {
        self.setCharAt(index, String(new))
    }

    public mutating func setCharAt(_ index: Int, _ new: String) {
        let i = self.index(self.startIndex, offsetBy: index)
        self.replaceSubrange(i...i, with: new)
    }
}

注意上面需要如何调用index(...)方法来将整数转换为实际索引!?看起来Swift像链表一样实现String,其中append(...)确实很快,但即使是找到索引(不对它做任何事情)也是一个线性时间操作(并且基于连接计数会变慢)。

ru9i0ody

ru9i0ody3#

String的下标操作符是get-only,这意味着只能使用它读取字符串,而必须使用其他操作符写入可变的String。
您可以解决此问题,并通过在name上使用map函数来清理代码

    • 雨燕4**
class Answer {
    var name = "name"
    var image: UIImage?
    var dashName = "name"
    var nameLength = 0

    init()
    {
        nameLength = name.count
        dashName = name.map { $0 == " " ? " " : "-" }.joined()
    }
}
    • 雨燕3**
class Answer {
    var name = "name"
    var image: UIImage?
    var dashName = "name"
    var nameLength = 0

    init()
    {
        nameLength = name.characters.count
        dashName = name.characters.map { $0 == " " ? String(" ") : String("-") }.joined()
    }
}

相关问题