返回可选值的类属性(字符串)(Swift)

时间:2016-02-23 00:50:14

标签: ios xcode swift

我在使用类的属性时遇到困难,该类将url存储为String。它返回Optional(“url”)而不仅仅是url。另一个字符串属性User.name没有同样的问题。当我访问它时,我已尝试解开该属性,但它无法正常工作,因为它告诉我它“无法强制解包非可选类型'String'的值”

详见

我创建了一个类似于

的类
import Foundation

class User {
    var name : String
    var age : Double
    var gender : String
    var imagelink : String

    init(name: String, age: Double, gender: String, imagelink: String) {
        self.name = name
        self.age = age
        self.gender = gender
        self.imagelink = imagelink
    }
}

用户正在一张桌子上听,当按下一个单元格时,它会进入一个新视图,我想要显示用户的个人资料信息和图像。

prepareforsegue就像这样设置

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "userCellPressed" {
        if let indexPath = tableView.indexPathForSelectedRow {
            let user = userList[indexPath.row]
            let controller = (segue.destinationViewController as! ProfileViewController)
            controller.detailUser = user
            controller.navigationItem.leftItemsSupplementBackButton = true
        }
    }
}

然后在新视图中,正确显示用户名,但由于detailUser.imagelink返回Optional(“url”)并且不允许我使用,因此不会显示图像!要么 ?因为它是一个字符串。

var detailUser: User? {
    didSet {
        configureView()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    configureView()
    // Do any additional setup after loading the view.
}

func configureView() {
    if let detailUser = detailUser {
        if let nameLabel = nameLabel, userImage = userImage {
            nameLabel.text = detailUser.name                

            let url = NSURL(string: detailUser.imagelink)
            let data = NSData(contentsOfURL:url!)
            if data != nil {
                userImage.image = UIImage(data:data!)
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您必须在使用之前解开网址。遵循您的语法将如下所示:

func configureView() {
    if let detailUser = detailUser {
        if let nameLabel = nameLabel, userImage = userImage {
            nameLabel.text = detailUser.name                

            if let url = NSURL(string: detailUser.imagelink) {
                let data = NSData(contentsOfURL:url)
                if data != nil {
                    userImage.image = UIImage(data:data!)
                }
            }
        }
    }
}

对于更易读的代码,我建议使用防护(未经测试):

更新了ASYNC请求:

func configureView() {
    // set name label
    guard let detailUser = detailUser else { return }
    guard let nameLabel = nameLabel else { return }
    nameLabel.text = detailUser.name

    // get weak copy of self to prevent retain cycle
    weak var weakSelf = self

    // retrieve and set user image
    guard let url = NSURL(string: detailUser.imagelink) else { return }
    NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: url), completionHandler: { data, response, error in
        // only carry on if self still exists and data was returned
        guard let strongSelf = weakSelf else { print("self released before response."); return }
        guard let data = data else { print("error retrieving image: \(error)"); return }

        // if userImage exists parse the data as an UIImage and set it
        strongSelf.userImage?.image = UIImage(data: data)
    }).resume()
}