ios 为什么我在 Swift 中得到这个“无法构造,因为它没有可访问的初始值设定项”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26596687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:23:25  来源:igfitidea点击:

Why do i get this in Swift "cannot be constructed because it has no accessible initializers"

iosswift

提问by RKD

Why do i get this in Swift "cannot be constructed because it has no accessible initializers":

为什么我在 Swift 中得到这个“无法构造,因为它没有可访问的初始值设定项”:

import Foundation

protocol Prototype {
    func Clone<T>() -> T
}

class myColor: Prototype {

    var red: Int?
    var green: Int?
    var blue: Int?

    init () {}

    func Clone<myColor>() -> myColor {

        let newColor = myColor()

        newColor.red = self.red
        newColor.green = self.green
        newColor.blue = self.blue


        return newColor
    }
}

The error is on line:

错误是在线:

let newColor = myColor()

回答by

Even if you set your framework to public, you still need to declare all classes you want to make accessible as 'public'. Same goes for your init method.

即使您将您的框架设置为公共,您仍然需要将您想要访问的所有类声明为“公共”。您的 init 方法也是如此。

public init() {
}

Did the trick for me.

对我有用。

回答by Rob Napier

First, classes have leading caps. Methods have leading lowercase. You mean MyColorand clone().

首先,类有领先的上限。方法有前导小写。你的意思是MyColorclone()

You're confusing the compiler at this point:

此时您正在混淆编译器:

func Clone<myColor>() -> myColor {

It thinks you mean that myColoris a type variable that is shadowing the class name. So when you get to myColor(), it's basically the same thing as T(), which has no trivial constructor.

它认为你的意思myColor是一个隐藏类名的类型变量。因此,当您到达 时myColor(),它与 基本相同T(),它没有简单的构造函数。

If you fix this stuff up, you'll find that the correct error is

如果你修复这些东西,你会发现正确的错误是

Type 'MyColor' does not conform to protocol 'Prototype'

Thaterror is a completely different problem. See Protocol func returning Selffor an explanation of how to implement a copy protocol. You also may be interested in the followup: Swift protocol and return types on global functions.

错误是一个完全不同的问题。有关如何实现复制协议的说明,请参阅返回 Self 的协议函数。您可能还对后续内容感兴趣:全局函数上的 Swift 协议和返回类型

回答by dimpiax

Seems generic generates extend of class, and need for use.

似乎泛型生成类的扩展,并且需要使用。

override init() {...

Note that any class in Swift must have initializer. And in your case nevertheless generic, class must have init()

请注意,Swift 中的任何类都必须具有初始化程序。并且在您的情况下仍然是通用的,类必须具有init()