Swift compiler cannot distinguish two initializers - swift

Basically, I have a class called UserData and multiple initializers for it. In particular, I have a copy initializer which looks like:
init (_ origin: UserData){
// copy over everything
}
And another initializer which is used when I need to read the data from a file:
convenience init (Read _: Bool) {
// read stuff and call another initializer
}
Then I always got a compiler error saying cannot convert Bool to UserData whenever I tried to do var something = UserData(true).
I tried adding label, but compiler said extroneous label since there is only one parameter. I could make a workaround by adding another random parameter to the second initializer. But why is the compiler always trying to interpret the call to something does not match the type while there is another that matches the type?

Swift has no problem distinguishing two initializers with one parameter. The error is because of how the second one is defined. It should be:
convenience init (_ read: Bool) {
// read stuff and call another initializer
}

Related

Swift - Ambiguous reference to member '==' error

I've done some searching and can't seem to find a solution for my below issue. I'm fairly new to swift so working through some issues. I have the below function which is just a stub containing the signature of the function and a return value just to get it to compile.
The test code is what I've been given, I did not write this and unfortunately cannot alter it.
My issues is that when I run it, it says that the test that calls this function has an "Ambiguous call to member '=='". I cannot alter the test code. Whatever the issue is must be in my function signature i'm assuming but could use some help.
Function That I am writing (That I assume contains the issue):
func contains(target: StringOrInt, compare: Character ) -> Bool {
return false
} // contains
Test that calls the function (I'm not allowed to edit this and did not write it):
func test_contains_cons_2_strings_3() {
let list1 = MyList.cons("foo", MyList.cons("bar", MyList.empty))
assertEquals(testName: "test_contains_cons_2_strings_3",
expected: true,
received: list1.contains(target: "bar", compare: ==))//Error is on this line '=='
} // test_contains_cons_2_strings_3
Error:
main.swift:807:67: error: ambiguous reference to member '=='
received: list1.contains(target: "foo", compare: ==))
Also note that "StringOrInt" is a protocol that I've defined that acts as an extension on both Int and String. This is done because the test code (Which i did not write and cannot edit) passes both strings and ints to this same variable and function.
Thanks advance for any help, I really appreciate it!
I think you want to compare two strings by passing "==" operator and return a Boolean value.If so you can use the below method,
func myList(_ compare:((String, String) -> Bool)) -> Bool {
return compare("foo","bar")
}
myList(==)
I was able to figure this out using the below. I implemented an enum of generic type and the nan extension on that enum. I then used this generic type within the contains function to represent multiple types instead of StringOrInt. Thanks everyone for the comments and the help.
enum implemented:
indirect enum my_list<A> {
case cons(A, my_list<A>)
case empty
}
I then implemented in extension for this enum "extension my_list" and placed the contains function within the extension.
contains function signature/stub:
func contains(target: A, compare:((A, A) -> Bool))
-> Bool {
return true
}// contains

Are Swift 4 custom argument labels ALWAYS required or just for disambiguation of functions?

This question is similar to
Swift 4 custom argument labels - required?
but more specific. I came across that question when researching a problem caused by changing from a var (requiring no parameter) to a func (requiring a parameter) but missed changing all references. I have created a playground that contradicts the claim made in a subsequent edit to that question: "question is incorrect, as custom labels are mandatory"
My question is: how to correctly express what I observed, as demonstrated below:
class SomeTest {
static func someParam(p1: String?) -> String? {
return "hello \(p1 ?? "nothing")"
}
// Uncommenting the following causes error at let funny
// static func someParam(p2: String?) -> String? {
// return "hello \(p2 ?? "nothing")"
// }
static func doIt() {
let funny = someParam // ignoring the argument label is ok if there is no ambiguity
funny("thing") // and can be used without
someParam(p1: "thing2") // must have argument label
}
}
SomeTest.doIt()
If you have both someParam functions (each with a differently named parameter), then the line:
let funny = someParam
no longer works since it isn't known which of the two someParam functions you are referring to. This is solved by providing an unambiguous name:
let funny = someParam(p1:) // or someParam(p2:)
Note that funny has a type of (String?) -> String?. Both someParam functions have that same type. This is why you need to provide more detail to disambiguate the two. The parameter names don't change the function type.
When directly calling a function you must provide the full function name which includes any named parameter labels.
But when you create a closure variable and assign it the value of a function, you don't need to provide more than the base name of the function if that name is unambiguous in the given context.

Swift: how to convert argument to argument name string?

In order to do logging nicely, I want to know how to convert argument to argument name string In Swift.
I already know Logging Method signature using swift.
I want to know how to log function argument as it is , following its value?
PS: I want to create a Util method helping logging.
func printMore(objName: Any){
print("objName: \(objName)")
}
the print("objName:..., I want the 'objName' injected automatically.
Suck as conditions:
let foo = "Sark"
print("foo: \(foo)")
PPS: It is about Swift runtime. After I alloc some memory, I create some objects, how to get them through runtime instead of hard coding.
Hm, if you called next method inside your function, it shows method declaration with all parameters:
func testFunction(param1: String, param2: String) {
print(#function)
}
testFunction(param1:param2:)
Write C .
U have to release it youself
object.description

What does this syntax mean in Swift?

I am new to Swift and am confused with this type of syntax. I know when you add () to the end of something you initialize it. I am still confused what this means though! I am adding code below.
Please help clarify what parenthesis at the end of this means! Thank you!
Also what does it mean to have all that code after the equal sign in this case? ( I know how to create a variable and add a String,Int or something like that to it).
I am just confused a bit wth this code.
Thanks for being understanding to a beginner!
var viewController: ViewController = {
return self.instantiateViewControllerWithIdentifier("Play") as ViewController
}()
EDIT 1 -
var statusBarStyle: UIStatusBarStyle = .Default {
didSet{
setNeedsStatusBarAppearanceUpdate()
}
}
{} declares a closure, which is anonymous function. Everything between { and } is a function body. Since closure defined in provided code does not have arguments it can be executed as regular function by (). { .. }() is just defining and immediately executing of anonymous function.
In a body of a function there is a call of instantiateViewControllerWithIdentifier("Play") which returns AnyObject. As viewController variable (var) expected to ba a type of ViewController, we cast AnyObject result of instantiateViewControllerWithIdentifier as ViewController
As for statusBarStyle, UIStatusBarStyle is an enum. .Default is one of enum's cases. It can be written alternatively as var statusBarStyle = UIStatusBarStyle.Default. The code that goes in the { ... } is a way to declare getter and setter behavior. In this particular case there is only one behavior didSet defined, which means as soon as value of UIStatusBarStyle updated (which is possible, as it is var), call function setNeedsStatusBarAppearanceUpdate. There are other getters & setters keywords that you may read about in Swift Book — https://itunes.apple.com/us/book/swift-programming-language/id881256329 such as get, set, willSet.
As Nikita said its instantly calling the anonymous function you declared. This is really useful as it allows you to add logic when initialising a var or let.
Since the function takes no arguments, it makes it harder to see at first that it actually is a function. An example with an argument makes this concept a lot clearer.
let oneMore: Int = { (num: Int) in num + 1 }(5) //oneMore = 6
We are creating a function that takes one Int argument num and implicitly returns an Int (the compiler knows this because of the type annotation on oneMore. By following the closure with (5) we are calling the anonymous function with the value of 5.
Hopefully this example makes it more clear what happening. Note for an anonymous function in the context we would never need to provide argument since it will only ever be called once with the arguments following it, so we can just include the argument within the function body.
let oneMore: Int = { 5 + 1 }()
In the second example the braces are allowing you to include property observers to the variable. an example of a property observer is didSet which is called each time after you assign a value to the variable. more info can be found in apples docs here.

Class instance variable initialization order?

Currently, I am seeing something strange behavior.
class DataManager1
{
let THE_ID = "SOME_ID_STRING"
let _con1 = CKContainer(identifier: THE_ID) // error
// error: 'DataManager1.Type' does not have a member named 'THE_ID'
}
class DataManager2
{
let THE_ID = "SOME_ID_STRING"
let _con1:CKContainer?
init()
{
_con1 = CKContainer(identifier: THE_ID) // no error.
}
}
In C++ we have a defined initialization order between instance member variables. I expected something similar, but actually I couldn't find a mention for that form the manual.
Does Swift has a defined initialization order of properties? If it does, what is the rule, and where can I find the rule?
This is due to the fact that you're using a Closure (a Function is just a special case of Closure that is unnamed) to initialize the _con1 property with a default value.
From the Apple provided iBook:
If you use a closure to initialize a property, remember that the rest
of the instance has not yet been initialized at the point that the
closure is executed. This means that you cannot access any other
property values from within your closure, even if those properties
have default values. You also cannot use the implicit self property,
or call any of the instance’s methods.
Even though the note above refers specifically to closures, it seems that trying to set the default value for a property to be that of another property directly also does not work.