gpt4 book ai didi

swift - 无法从计算属性中为存储属性赋值

转载 作者:IT王子 更新时间:2023-10-29 05:18:45 26 4
gpt4 key购买 nike

我创建了一个结构,其中我有一个属性“_photo”,它是在调用计算属性“photo”时延迟分配的。我不断收到错误

Cannot assign to '_photo' in 'self'

这是代码。我用 Swift 1.1 (photo1) 和 swift 1.2 (photo2) 语法编写了计算方法。两者都给出与上述相同的编译时错误。

需要进行哪些更改才能修复该错误?

import UIKit

public struct PhotoStruct {
var _photo:UIImage?
var urlString:String?

init(image:UIImage?, url:String?){
self._photo = image
self.urlString = url

}

init(url:String?){
self.urlString = url
}


var photo1:UIImage? {

if let theURL = self._photo {
return self._photo
}else{
if let urlString = self.urlString{
if let url = NSURL(string: urlString as String){
if let imageData :NSData = NSData(contentsOfURL: url){
if let image:UIImage = UIImage(data:imageData){

self._photo = image //** Cannot assign error is here**
}
}
}
}
return self._photo
}
}

var photo2:UIImage? {

if let theURL = self._photo {
return self._photo
}else{
if let urlString = self.urlString,
url = NSURL(string: urlString as String),
imageData :NSData = NSData(contentsOfURL: url),
image:UIImage = UIImage(data:imageData){

self._photo = image //** Cannot assign error is here**
}
return self._photo
}
}



}

最佳答案

至于struct,如果你想改变计算属性中的self属性,你必须显式声明getter为mutating get { .. }

public struct PhotoStruct {
var _photo:UIImage?
var urlString:String?

init(image:UIImage?, url:String?){
self._photo = image
self.urlString = url
}

init(url:String?){
self.urlString = url
}

var photo1:UIImage? {
mutating get {
// ^^^^^^^^^^^^
// you can set `self._photo = image` here
}
}

var photo2:UIImage? {
mutating get {
// ^^^^^^^^^^^^
// you can set `self._photo = image` here
}
}
}

当然,结构本身必须是可变的:

var pVar:PhotoStruct = PhotoStruct(image: nil, url: nil)
pVar.photo1 // no problem
let pLet:PhotoStruct = PhotoStruct(image: nil, url: nil)
pLet.photo1 // < [!] error: immutable value of type 'PhotoStruct' only has mutating members named 'photo1'

一个警告:

据我所知,mutating get { } 功能未记录在 the language reference 上.

关于swift - 无法从计算属性中为存储属性赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28565900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com