Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode does not autocomplete memberwise initializer of a Struct

Tags:

xcode

swift

I am defining a struct like this in the Point.swift inside of my Xcode Project file:

struct Point {
    var x: Int
    var y: Int
}

If i am trying to init the Point struct from another file, Xcode does not autocompleting the memberwise initializer. Even if I have been restarted the machine as some friends suggest.

screenshot

BUT autocompletion works fine, if i am defining initialising a new Instance in the same file or playground.

screenshot

Any ideas how to fix this autocompletion issue?

like image 393
Alex Avatar asked Jan 30 '16 12:01

Alex


People also ask

Why is autocomplete not working Xcode?

This can happen when the file is not a member of the Target. Open the file where autocomplete is not working and show the the "Utilities" tab in the top right of Xcode (blue in the screenshot below). Ensure your Target (typically your app's name) is checked.

What is memberwise initializer?

The memberwise initializer is a shorthand way to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name. The example below defines a structure called Size with two properties called width and height .

Do structs have Initializers?

In Swift, types defined as structs automatically get a default initializer synthesized by the compiler — a so-called “memberwise initializer”, as the compiler will generate it based on the given struct's members (that is, its stored properties).

How do you initialize a struct in Swift?

An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }


2 Answers

This appears to just be a bug in Xcode. The first time you use an instance in another file, Xcode does not provide the autocompletion. But, the second time you use it it does.

Here is a demo of the strange behavior I am seeing. Even with the Point.swift file saved, the first time I use Point in ViewController.swift it doesn't autocomplete, but the second time it does:

Demo of strange autocomplete behavior

This is with Xcode 7.2.

like image 77
vacawama Avatar answered Sep 27 '22 15:09

vacawama


This bug is still actual in Xcode 10. As an addition to top answer: you can use explicit .init for autocomplete and then delete .init.

  1. Get autocomplete to work with explicit init:

Point.init(x: x, y: y)

  1. Delete .init and you'll end up with the expected code:

Point(x: x, y: y)

like image 8
mbabaev Avatar answered Sep 30 '22 15:09

mbabaev