swift - 使用用户定义的类
问题描述
我正在尝试实例化一个名为 Rock 的用户定义对象。在这段代码中,“contains”是 Item 类型的变量,Rock 和 Bug 都是 Item 的子类。当我尝试实例化 Rock 时,代码会生成错误,但不会生成 Bug。这不是您实例化类的方式吗?它说“无法将 Rock.Type 类型的值分配给类型‘项目’。
另外,我想知道如何编写代码来询问对象“包含”它包含的对象类别。有那个功能吗?
for r in 0...map.MAXROWS{
for c in 0...map.MAXCOLUMNS{
if (r < 3) || (r > (MAXROWS - 3)){
self.contains = Rock
}else if (c < 3) || (c > (MAXCOLUMNS - 3)){
self.contains = Rock
}else if (r == 3) && (c == 100){
self.contains = Bug(index: 1, map: map)
}else if (arc4random() * 100 == 1){
self.contains = Bug(index: current, map: map)
current = current + 1
}else if (arc4random() * 8) == 1{
self.contains = Rock
}
}
}
import Cocoa
class Bug: Item {
var male = true
var direction = 1
var appearance = 1
var positionRow = 0
var positionColumn = 0
// Direction:
// 1 = Up
// 2 = Right
// 3 = Down
// 4 = Left
init(index: Int, map: Map){
super.init()
map.initializeBugs(index: index, current: self)
if (index == 1){
self.direction = 3
self.positionRow = 3
self.positionColumn = 100
}else{
self.direction = (Int(arc4random() * 4)) + 1
}
Birth(index: index)
}
func Birth(index: Int){
if (arc4random() * 8) == 1{
self.male = false
}else{
self.male = true
if (arc4random() * 2) == 1{
self.appearance = 1
}else{
self.appearance = 2
}
}
}
func DisplayBug() -> Int{
if self.male == false{
return self.direction
}else{
if self.appearance == 1{
switch self.direction{
case 1:
return 5
case 2:
return 6
case 3:
return 7
case 4:
return 8
default:
return 0
}
}else if self.appearance == 2{
switch self.direction{
case 1:
return 9
case 2:
return 10
case 3:
return 11
case 4:
return 12
default:
return 0
}
}
}
}
func WhereAreYouRow() -> Int{
return self.positionRow
}
func WhereAreYouColumn() -> Int{
return self.positionColumn
}
func AreYouBug() -> Bool{
return true
}
func InstantiateBug{
}
}
import Cocoa
class Rock: Item {
override init(){
super.init()
}
func AreYouRock() -> Bool{
return true
}
解决方案
您需要使用构造函数来实例化类,例如:Rock()
或Bug()
当只调用Rock
orBug
时,如果没有()
引用类,您想要做的是创建一个对象,因此您需要()
简而言之:
课程:Rock
,Bug
对象:Rock()
,Bug()
所以在你的代码中,你想指定self.contains = Object
这意味着:
self.contains = Rock()
或者self.contains = Bug()
推荐阅读
- c# - C# 对象不解析为 int
- reactjs - `rexxars/react-markdown` 插件使用或渲染 React markdown 的替代方法
- php - 如何使用 PHP 发送包含 youtube 视频的电子邮件
- azure - 应用程序网关 URL 路由到多个应用程序服务
- python - 编写python函数时的自动弹出参数方法和属性
- android - 无法在 Anko 中预览
- regex - 如何使用 RegEx 匹配这个?
- python - 在我尝试使用 Python 中的快速排序算法时遇到递归问题
- python - 以编程方式查找为给定 PID 打开的端口
- renderscript - 偶尔的 RenderScript 加载失败 - ScriptC 脚本加载失败