Swift:实例成员不能用于

时间:2016-05-27 05:14:27

标签: swift2 singleton

我试图在Users课程中调用Data课程中的变量,但我发现此错误

  

实例成员'用户'不能用于类型'数据'

Data班级代码:

import Foundation

class Data {

   static let sharedInstance = Data()

   let user = Users()
   var id = (user.userId).string

   //Login.swift
   static let quarterlyEndpoint: String = "http://anyapi/api/users/\(id)/quarterly/tasks"

// for prevent from creating this class object
private init() { }

}

Users班级代码:

var userId: Int {

    guard let  _userId = getId() else {
        return 0
    }

    return _userId
}

更新

我可以调用该函数,但是当我打印weeklyEnd时,我会得到http://anyapi/api/users/(Function)/quarterly/tasks而不是http://anyapi/api/users/3/quarterly/tasks

let user = Users()

func getId() -> String
{
    let id = String(user.userId)
    return id
}

static let weeklyEndpoint: String = "http://anyapi/api/users/\(getId)/quarterly/tasks"

更新2

import Foundation

class Data {

static let sharedInstance = Data()

let user = Users()
let id:String?
let weeklyEndpoint: String?

// for prevent from creating this class object
private init() {
    id   = String((user.userId))
    //Login.swift
    weeklyEndpoint = "http://anyapi/api/users/\(id)/quarterly/tasks"
}

}

我无法在weeklyEndPoint课程外拨打Data。我已经尝试了Data.weeklyEndPoint,但它无法正常工作

1 个答案:

答案 0 :(得分:1)

尝试像这样在Data类中创建一个方法。

func getusrid ()-> String
{
 var id = (user.userId).string
return id ;

}

您无法从任何方法之外的实例变量中获取值

编辑:

class Data {

    static let sharedInstance = Data()
    let id:String?
    let quarterlyEndpoint: String?

    let user = Users()
  private init()
   {
     id   = String((user.userId))
     quarterlyEndpoint = "http://anyapi/api/users/\(id)/quarterly/tasks"

    }




}