Hello I am implementing a graph data structure. When I try to build the application the I get the error «Editor placeholder in source file»
The full graph implementation was pulled from WayneBishop’s GitHub from here https://github.com/waynewbishop/SwiftStructures
class Path {
var total: Int!
var destination: Node
var previous: Path!
init(){
//Error happens on next line
destination = Node(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double)
}
}
I changed the Node Class around to:
public class Node{
var key: String?
var neighbors: [Edge!]
var visited: Bool = false
var lat: Double
var long: Double
init(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double) {
self.neighbors = [Edge!]()
}
}
This Error happens 5 times throughout the code that I have built so far. Also this question has been asked, but not answered.
I think the error may be due to my changes to the init() in the Node class. Prior to my changes it was just init(). If it is, how can I add objects to the class? Pardon me if I am not correct in my programming terminology, as I am relatively new to OOP.
Hi everyone. I’m new to using Xcode and this is my first time coding. I’m currently following some tutorials that require this coding to create a rectangle:
let canvas = UIView(frame: CGRectMake(0, 0, 200, 200)). I know that CGRectMake was removed from xcode so I changed my code to
let canvas = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
I’m getting a swift compiler warning of ‘editor placeholder in source file’. Can someone tell me how to fix this and why i’m getting it?
Accepted Reply
When you insert code via autocompletion (or via a code snippet, sometimes), there may be placeholders — blue rectangles that describe what you should put there instead. You can click on a placeholder to select it, then type your actual code.
For example (I’m guessing) when you typed «UIView(«, you inserted a complete call, but with a «CGRect» placeholder where the rect was supposed to go. If you put the rect parameters after the placeholder without replacing it, you’d get this error message. You should have replaced the placeholder, not used it as code.
If that’s what happened, you don’t have to actually retype it in this case. If you double-click on a placeholder (or select it and press Enter), it will change to regular text.
Replies
When you insert code via autocompletion (or via a code snippet, sometimes), there may be placeholders — blue rectangles that describe what you should put there instead. You can click on a placeholder to select it, then type your actual code.
For example (I’m guessing) when you typed «UIView(«, you inserted a complete call, but with a «CGRect» placeholder where the rect was supposed to go. If you put the rect parameters after the placeholder without replacing it, you’d get this error message. You should have replaced the placeholder, not used it as code.
If that’s what happened, you don’t have to actually retype it in this case. If you double-click on a placeholder (or select it and press Enter), it will change to regular text.
That’s exactly what I did by the looks of it. I’ve double-clicked and its changed and given me the rectangle I needed. Thanks!
Command + Shift + b
It works perfectly… I have already done this for tableView
In addition to the solution offered by Quincey Morris, if you can’t find said placeholder, try closing and reopening your project, or even Xcode.
Thank you @Anam098 it worked.
Привет, у меня проблема с быстрой ошибкой «Заполнитель Swift Editor в исходном файле» Это мой код
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: <#T##IndexPath#>) as! CustomBrandCell
let brandImage: UIImage = UIImage(named: self.brands[indexPath.row].name)!
cell.brandImageView.image = brandImage
return cell
}
3 ответа
Лучший ответ
Я много раз встречал тот же вопрос на SO. Но ни один из них не дал ответа, которого я искал.
Вы получаете Placeholder in source file, когда у вас есть один из них (где написано «String» на синем фоне) в вашем коде.

Заполнитель для нас, программистов. Он говорит: «Здесь должно быть значение типа String». Вы можете щелкнуть по нему и начать вводить, чтобы просто заменить его, например, именем переменной. Вы также можете нажать вкладку, чтобы автоматически выбрать следующий заполнитель. Это очень полезно, когда вы вызываете функцию с несколькими параметрами (и, следовательно, с несколькими заполнителями).
Заполнитель на самом деле представляет собой обычный текст (<# T ## Strign #>), но XCode «переводит» его так, чтобы он выглядел так, как он есть.
В вашем случае ошибка находится в третьей строке.
...withReuseIdentifier: "Cell", for: <#T##IndexPath#>) as! CustomBrandCell
Как видите, <#T##IndexPath#> является заполнителем обычного текста, как я упоминал ранее. Вы, наверное, хотите, чтобы это было indexPath
16
ntoonio
30 Апр 2018 в 19:32
Попробуй это. надеюсь решить твою проблему
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
// get a reference to your storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath) as! CustomBrandCell
let brandImage: UIImage = UIImage(named: self.brands[indexPath.row].name)!
cell.brandImageView.image = brandImage
return cell
}
0
Museer Ahamad Ansari
19 Дек 2016 в 12:52
Попробуйте cmd + shift + k, чтобы очистить проект и снова запустить код. Это устранило проблему для меня.
1
Techie
30 Мар 2020 в 15:08
Здравствуйте, я реализую структуру данных графа. Когда я пытаюсь создать приложение, я получаю сообщение об ошибке «Заполнитель редактора в исходном файле»
Полная реализация графа была вытащена из WayneBishop GitHub здесь https://github.com/waynewbishop/SwiftStructures
class Path {
var total: Int!
var destination: Node
var previous: Path!
init(){
//Error happens on next line
destination = Node(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double)
}
}
Я изменил класс Node вокруг:
public class Node{
var key: String?
var neighbors: [Edge!]
var visited: Bool = false
var lat: Double
var long: Double
init(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double) {
self.neighbors = [Edge!]()
}
}
Эта ошибка происходит 5 раз в течение всего кода, который я создал до сих пор. Также этот вопрос задан, но не ответил.
Я думаю, что ошибка может быть связана с моими изменениями в init() в классе Node. До моих изменений это было просто init(). Если это так, как добавить объекты в класс? Простите меня, если я не прав в своей терминологии программирования, поскольку я относительно новичок в ООП.
Ответ 1
у вас было это
destination = Node(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double)
который был надписью владельца места выше, вам нужно вставить некоторые значения
class Edge{
}
public class Node{
var key: String?
var neighbors: [Edge]
var visited: Bool = false
var lat: Double
var long: Double
init(key: String?, neighbors: [Edge], visited: Bool, lat: Double, long: Double) {
self.neighbors = [Edge]()
self.key = key
self.visited = visited
self.lat = lat
self.long = long
}
}
class Path {
var total: Int!
var destination: Node
var previous: Path!
init(){
destination = Node(key: "", neighbors: [], visited: true, lat: 12.2, long: 22.2)
}
}
Ответ 2
Иногда XCode не забывает строку с «Заместителем редактора», даже если вы заменили ее значением. Отрежьте часть кода, где XCode жалуется, и вставьте код обратно в то же место, чтобы сообщение об ошибке исчезло. Это сработало для меня.
Ответ 3
После Ctrl + Shift + B проект работает нормально.
Ответ 4
Ошибка прямолинейна и ее из-за неправильных заполнителей, которые вы использовали при вызове функции. Внутри init вы не передаете какие-либо параметры своей функции. Это должно быть так.
destination = Node("some key", neighbors: [edge1 , edge2], visited: true, lat: 23.45, long: 45.67) // fill up with your dummy values
Или вы можете просто инициализировать методом по умолчанию
destination = Node()
UPDATE
Добавьте пустой инициализатор в класс Node
init() {
}
Ответ 5
Если у вас есть эта ошибка, когда вы создаете сегменты с контроллерами представления, а не с элементами пользовательского интерфейса, вы должны изменить sender: Any? к этому
@IBAction func backButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "goToMainScreen", sender: self)
}
Это будет работать.
Ответ 6
Папка «Чистая сборка»
+
построить
очистит любую ошибку, которая может у вас возникнуть, даже после исправления вашего кода.