简体   繁体   中英

How do I call a static method from another class in swift?

This is Selection class:

public class Selection {
  var anchor: Point
  var focus: Point
  var dirty: Bool
  var format: Int

  init(anchor: Point, focus: Point, format: Int) {
    self.anchor = anchor
    self.focus = focus
    self.dirty = false
    self.format = format
  }

  public func getSelection() -> Selection? {
    let state = getActiveState()
    return state?.selection
  }
} 

State class:

public func getActiveState() -> State? {
  return Thread.current.threadDictionary[activeStateThreadDictionaryKey] as? State
}

How do I call getSelection() in Text class?

When I try to call the getSelection() in Text class, let selection = getSelection() I get this error - This method is defined on selection, and may not be available in this context.

I agree with @jnpdx we cannot see where getActiveState is located. Meaning...what class is it in for example. You mention getActiveState is in a class but no additional information about that class. Aside from Access Controls on that class you should be able to declare and call in the following manner:

//Declaration:

public class Selection {
    
    public func getSelection() {
        print("Get selection")
    }
}

//Call Site:

let mySelection = Selection()
mySelection.getSelection()

Like @jnpdx mentioned we are not aware of the location of getActiveState so we are not aware of the Access Controls around that class. That could be the culprit related to this particular issue. The access controls page in Swift Documentation is a handy read. You can find that page at Swift Access Controls

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM