[英]How to access a String from another class in swift?
I have two classes , one is called the ViewController
which looks like this 我有两个类,一个叫做
ViewController
,看起来像这样
import UIKit
class ViewController: UIViewController {
let demoURLs = DemoURLs
let ImgURL = NSURL(string: demoURLs.photoURL)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}
The demoURLs.swift
file looks like this demoURLs.swift
文件如下所示
import Foundation
struct DemoURLs{
var photoURL = " xyz " }
But I get an error. 但是我得到一个错误。 I understand that my method is incorrect.
我了解我的方法不正确。 What is the correct way of accessing this string , so that I can use it in an
NSString
? 什么是访问此字符串的正确方法,以便可以在
NSString
使用它? My final aim is to inflate an imageView
with an image from this URL. 我的最终目的是为了虚增
imageView
与该URL的图像。
The way you are instantiating the struct is incorrect. 您实例化结构的方法不正确。 Change
更改
let demoURLs = DemoURLs
to 至
let demoURLs = DemoURLs() // the () calls init()
and you will be able to access the members of the struct. 并且您将能够访问该结构的成员。
struct DemoURLs {
static var photoURL = " xyz "
}
should do the job. 应该做的工作。
To read, from any class use: 要从任何类阅读,请使用:
let myString = DemoURLs.photoURL
To write: 来写:
DemoURLs.photoURL = "new name for xyz"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.