【问题标题】:cannot assign to property .... setter in accesible swift 3无法分配给属性 .... 可访问的 swift 3 中的设置器
【发布时间】:2017-04-05 13:28:00
【问题描述】:

我正在尝试从 Web api 获取艺术家信息并使用返回的数据创建一个新的艺术家类,但是我无法将我的类属性设置为返回的数据。这是我的代码

导入基础 类 TrackList {

static var trackService:TrackService?

static func getArtistFromService()-> Artist
{
    // construct the complete URL endpoint ot be called

    //let searchURL = "https://\(siteURL)/?s=\(searchTerm)"
    var searchedartist : Artist

    let searchURL = "http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks&artist=drake&api_key=d932ba18a79b1739a4d9ba02c63bdb61&format=json"

    // degugging - can test in browser if call is failing
    print ("Web Service call = \(searchURL)")

    // create the Web Service object that will make the call - initialiser
    trackService = TrackService(searchURL)

    // create an operation queue - to allow the web service to be called on a secondary thread...
    let operationQ = OperationQueue()
    //... will only allow one task at a time in queue...
    operationQ.maxConcurrentOperationCount = 1
    //...queue that web service object as the operation object to be run on this thread
    operationQ.addOperation(trackService!)
    //... wait for the operation to complete [Synchronous] - better to use delegation, for [Asynchronous]
    operationQ.waitUntilAllOperationsAreFinished()

    // clear the current list of movies
    // get the raw JSON back from the completed service call [complete dataset]
    let returnedJSON = trackService!.jsonFromResponse

    let artist = returnedJSON?["artist"] as! String
    let bio = returnedJSON?["bio"] as! String

          searchedartist.name = artist
        searchedartist.bio = bio


    // return the main list of Movie objects to caller (UI)

    return searchedartist
}


// for debugging - displays some details of the Movies currently in the main list...

} // 类声明结束

类艺术家 { 私有(设置)变量名称:字符串 私有(设置)var bio:字符串

init?(_ n:String, _ b:String)
{
    name = n
    bio = b

}

convenience init(_ JSONObject:[String:String])
{
    let name = JSONObject["name"]!
    let bio = JSONObject["bio"]!

    self.init(name, bio)!
}

}

【问题讨论】:

  • 什么是TrackService?请稍微格式化一下代码,以便正确显示

标签: swift xcode mobile get set


【解决方案1】:

您的班级有私人二传手。只需使用返回的数据创建一个新艺术家:

let artist = returnedJSON.....
let bio = returnedJSON.....

let searchedArtist = Artist(artist, bio)
return searchedArtist

或者只是使用您方便的 init。一般来说,我更喜欢拥有不可变的模型对象,所以我不建议将你的设置器公开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多