Viewcontroller.Type Does Not Have a Member Names 'Answerone' - Swift

ViewController.Type does not have a member names 'answerOne' - SWIFT

Solution 1 : Your code is not inside a method, you have to wrap it inside the method. Check this stackoverflow answer

Solution 2 : Keep your questions and answers inside struct and access them, if you don't want to wrap it inside a function.

struct firstQuestion {
static var question = "What was the first planet to be discovered using the telescope, in 1781?"
static var answerOne = "Mercury"
static var answerTwo = "Uranus"
static var answerThree = "Venus"
static var answerFour = "Jupiter"
static var correctAnswer = "Correct Answer"
}

var questionOneArray = [firstQuestion.answerOne, firstQuestion.answerTwo, firstQuestion.answerThree, firstQuestion.answerFour, firstQuestion.correctAnswer]

Swift: 'ViewController.Type' does not have a member named 'URL'

None of your code is in a method, wrap it up in a method and call the method when appropriate.

Type Has No Subscript Members?

Add a subscript to your Ship object to return an optional Coordinate:

subscript(index: Int) -> Coordinate? {
guard let coordinate = shipCoors?[index] else {
return nil
}
return coordinate
}

shipCoors is declared as [Coordinate]? (an optional array), so there's a risk a Ship won't have an array in shipCoors. In this case I return nil, but you can return whatever you want instead.

Why do I need underscores in swift?

There are a few nuances to different use cases, but generally an underscore means "ignore this".


When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing. A fuller function declaration looks like this:

func myFunc(label name: Int) // call it like myFunc(label: 3)

"label" is an argument label, and must be present when you call the function. (And since Swift 3, labels are required for all arguments by default.) "name" is the variable name for that argument that you use inside the function. A shorter form looks like this:

func myFunc(name: Int) // call it like myFunc(name: 3)

This is a shortcut that lets you use the same word for both external argument label and internal parameter name. It's equivalent to func myFunc(name name: Int).

If you want your function to be callable without parameter labels, you use the underscore _ to make the label be nothing/ignored. (In that case you have to provide an internal name if you want to be able to use the parameter.)

func myFunc(_ name: Int) // call it like myFunc(3)

In an assignment statement, an underscore means "don't assign to anything". You can use this if you want to call a function that returns a result but don't care about the returned value.

_ = someFunction()

Or, like in the article you linked to, to ignore one element of a returned tuple:

let (x, _) = someFunctionThatReturnsXandY()

When you write a closure that implements some defined function type, you can use the underscore to ignore certain parameters.

PHPhotoLibrary.performChanges( { /* some changes */ },
completionHandler: { success, _ in // don't care about error
if success { print("yay") }
})

Similarly, when declaring a function that adopts a protocol or overrides a superclass method, you can use _ for parameter names to ignore parameters. Since the protocol/superclass might also define that the parameter has no label, you can even end up with two underscores in a row.

class MyView: NSView {
override func mouseDown(with _: NSEvent) {
// don't care about event, do same thing for every mouse down
}
override func draw(_ _: NSRect) {
// don't care about dirty rect, always redraw the whole view
}
}

Somewhat related to the last two styles: when using a flow control construct that binds a local variable/constant, you can use _ to ignore it. For example, if you want to iterate a sequence without needing access to its members:

for _ in 1...20 { // or 0..<20
// do something 20 times
}

If you're binding tuple cases in a switch statement, the underscore can work as a wildcard, as in this example (shortened from one in The Swift Programming Language):

switch somePoint { // somePoint is an (Int, Int) tuple
case (0, 0):
print("(0, 0) is at the origin")
case (_, 0):
print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
print("(0, \(somePoint.1)) is on the y-axis")
default:
print("(\(somePoint.0), \(somePoint.1)) isn't on an axis")
}

One last thing that's not quite related, but which I'll include since (as noted by comments) it seems to lead people here: An underscore in an identifier — e.g. var _foo, func do_the_thing(), struct Stuff_ — means nothing in particular to Swift, but has a few uses among programmers.

Underscores within a name are a style choice, but not preferred in the Swift community, which has strong conventions about using UpperCamelCase for types and lowerCamelCase for all other symbols.

Prefixing or suffixing a symbol name with underscore is a style convention, historically used to distinguish private/internal-use-only symbols from exported API. However, Swift has access modifiers for that, so this convention generally is seen as non-idiomatic in Swift.

A few symbols with double-underscore prefixes (func __foo()) lurk in the depths of Apple's SDKs: These are (Obj)C symbols imported into Swift using the NS_REFINED_FOR_SWIFT attribute. Apple uses that when they want to make a "more Swifty" version of an (Obj)C API — for example, to make a type-agnostic method into a generic method. They need to use the imported API to make the refined Swift version work, so they use the __ to keep it available while hiding it from most tools and documentation.

Swift 'unable to dequeue a cell with identifier intervalCellIdentifier

1. With XIB file

You have to register the cell to table first, may be in viewDidLoad, as:

let nib = UINib(nibName: "CustomCell", bundle: NSBundle.mainBundle()) 
tableView.registerNib(nib, forCellReuseIdentifier: "CustomCellIdentifier")

This is applicable if we are using a custom cell with .xib file.

2. Without XIB file

And here is a solution if we are not creating separate .xib file for custom cell:

We need to create dynamic prototype for cell in table view as:
Sample Image

Then we need to provide class name and reuse identifier for our custom cell as:
Sample Image

Sample Image
Here, no need to register class or nib!


Here is the cellForRowAtIndexPath implementation:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

// Configure the cell...
let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCellId", forIndexPath: indexPath) as! CustomTableViewCell
cell.setCellIndexLabel(indexPath.row)

return cell
}

This implementation will be same for both the above solutions.


3. Only Class Implementation
Without XIB, without Dynamic Prototype

Here is the custom cell without any XIB or Dynamic Prototype:

class WithoutNibCustomTableViewCell: UITableViewCell {

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
//do custom initialisation here, if any
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}

class func identifier() -> String {
return "WithoutNibCustomTableViewCellId"
}

//MARK: Public Methods
func setCellIndexLabel(index: Int) {
let customLbl = UILabel(frame: CGRectMake(0, 0, 100, 40))
customLbl.text = String(index)
contentView.addSubview(customLbl)
}

}

Then, in table view, we need to register cell class as:

tableView!.registerClass(WithoutNibCustomTableViewCell.classForCoder(), forCellReuseIdentifier: WithoutNibCustomTableViewCell.identifier())

cellForRowAtIndexPath also same as above, like:

let cell = tableView.dequeueReusableCellWithIdentifier(WithoutNibCustomTableViewCell.identifier(), forIndexPath: indexPath) as! WithoutNibCustomTableViewCell
cell.setCellIndexLabel(indexPath.row)
return cell

iOS How to fetch next row parse Swift

Ok so with parse you probably dont want to keep calling the server every single time so what you want to do is get your data append it to and array and then just get the information at each index. There are a lot of ways to do this but I'm going to show a simple way to do this. The more you get into parse you can use PFSubclassing and that is a better way to handle your data but for now just do it like this. Create this as a new class

Class QuestionManager{
var question: String?
var answerA: String?
var answerB: String?
var answerC: String?
var answerD: String?

}

In the first class do this.

var questions = [QuestionManager]()
var arrayIndex = 0
let query = PFQuery(className: "test")
query.findObjectsInBackground{ (objects, error) in
if error == nil && objects != nil {
for object in objects as? [PFObject]{
self.questions.append(QuestionManager(
question: object!["question"] as! String,
answerA: object!["answer1"] as! String,
answerB: object!["answer2"] as! String,
answerC: object!["answer3"] as! String,
answerD: object!["answer4"] as! String

))
}
} else {
print("Error")
}

Then two access it just have the index of the array change

self.label.text = questions[arrayIndex].question

Each time you add one to the array it will return the next set of questions and answers

If you need clarification let me know

How to get access to constants from separate .swift file

In your example, you've defined a class, Questions, that has a constant member variable. However, you need to create an "instance" of that class in order to access its member variable:

public class Questions {
let question1 = [ etc. ]
}

var basicQuestionBank: [[String:String]] = []

func addToQuestionBankOne() {
// qs is an instance of the Questions class
let qs = Questions()
// and has a member variable, question1
basicQuestionBank.append(qs.question1)
}

Classes are like templates. You create instances of classes (these are called objects) that all have the same member variables and methods, but that can hold different values in their member variables.

In this case, it might seem a bit confusing, because you've created a class that has only one member, which is a let (so it can never hold anything other than its initial value), and no init method (which is the only place you could set question1 to be anything different than the default value you've given it). But nonetheless, you can only access that value by creating an instance of Questions, then accessing the question1 property on that instance.

By the way, for your next step you might want to try representing your questions as a struct, rather than a dictionary of strings:

struct QandA {
let question: String
let answers: [String]
let correctAnswer: Int
let questionNumber: String
}

let question1 = QandA(
question: "A square has how many sides?",
answers: ["One","Two","Three","Four"],
correctAnswer: 4,
questionNumber: "A-001-001")

Putting your data in a structure like this makes it much easier to operate on:

println(question1.question)
for (number, answer) in enumerate(question1.answers) {
println("\(number): \(answer)")
}

Just like above, this is creating an instance of the QandA struct (structs are similar to classes – the Swift book has more details on the differences), called question1, then accessing the properties of this instance.



Related Topics



Leave a reply



Submit