【问题标题】:Property declared in my class isn't recognized when attempting to use it inside a function?尝试在函数中使用我的类中声明的属性时无法识别它?
【发布时间】:2023-03-07 10:58:01
【问题描述】:

我检查了该属性的拼写错误,绝对不是这种情况。我正在尝试使用我在parseSongs() 函数内的类中声明的属性mySong

该函数不在类中,但在同一个文件中。该类的目标成员资格设置为项目名称,其他文件也是如此。

我很困惑为什么编译器无法识别parseSongs() 中我的属性名称?

我可以在类之外声明该属性,但即使它是在类中声明的,我也应该能够使用它。

import UIKit

class SongsTableViewController: UITableViewController {

//A property that is an array of type 'Song'
var mySong = [Song]()

private let cache = NSCache()

private func fetchMyData(){

    let myUrl = NSURL(string: "http://itunes.apple.com/search?term=beatles&country=us")!
    let mySession = NSURLSession.sharedSession()

    //The work to be queued initiates
    let myTask = mySession.dataTaskWithURL(myUrl){
    //This closure right here is the Completion Handler

        data, response, error in
        if error != nil{
            //Handle error

        }else{

            let myHttpResponse = response as! NSHTTPURLResponse
            switch myHttpResponse.statusCode {
            case 200..<300:
                print("OK")
                print("data: \(data)")
            default: print("request failed: \(myHttpResponse.statusCode)")

            }
        }
    }
    myTask.resume()
 }

}

func parseJson(myData data: NSData){

do{

    let json: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: [])
    if let unwrappedJson: AnyObject = json{

        parseSongs(unwrappedJson)
    }
}catch{

 }
}


 func parseSongs(json1: AnyObject){
     mySong = []

    //Optional Binding
    if let array = json1["results"] as? [[String:AnyObject]]{
        //For-In loop
        for songDictionary in array{

            if let title = songDictionary["trackName"] as? NSString{

                if let artist = songDictionary["artistName"] as? NSString{

                    if let albumName = songDictionary ["collectionName"] as? NSString{

                        if let artWorkUrl = songDictionary["artWorkUrl100"] as? NSString {
                            let song = Song(artist: (artist as String), title: (title as String), albumName: (albumName as String), artWorkUrl: (artWorkUrl as String))

                            mySong.append(song)
                        }
                    }

                }
            }
        }

        dispatch_async(dispatch_get_main_queue()){
            self.tableView.reloadData()
        }
    }
}

【问题讨论】:

    标签: swift properties declaration


    【解决方案1】:

    要使用在类中声明的外部属性,您必须遵循此

     SongsTableViewController().theProperty
    

    如果你在类外声明它,那么你可以在类外的函数中访问它

    【讨论】:

    • 我明白了,但它不是类属性而是实例属性,所以我不应该能够使用它而不必通过点语法访问它吗?
    • 正如你所说的它是一个实例属性,所以直到我不知道其他方式。 :)
    • 我刚刚编辑了问题并包含了它的属性。我拿这个例子的书的作者,mySong = []他没有SongsTableViewController().mySong吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多