最近开始学习iOS的游戏开发,正好看到一个系列的教程(https://www.bloc.io/tutorials/swiftris-build-your-first-ios-game-with-swift#!/chapters/675),还用的是Swift,于是就决定开始学习用swift开发。
我这系列blog就依照在swift的学习过程中碰到的问题,然后做一个记录和总计,以备后续复习。
super.init(size: size)
anchorPoint = CGPoint(x: 0, y: 1.0)
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: 0, y: 0)
background.anchorPoint = CGPoint(x: 0, y: 1.0)
addChild(background)
1. Let和Var
接触到了swift的第一个关键字 let,万能的stackoverflow上面有个回答讲述的非常全面: The: let
keyword defines a constant:
let theAnswer = 42
The theAnswer
cannot be changed afterwards.
The var
defines an ordinary variable:
What is interesting:
The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.
Another strange feature:
通俗的讲,let定义的是一个常亮,而var定义的是一个变量You can use almost any character you like for constant and variable names, including Unicode characters:
Both var
and let
are references, therefore let
is a const reference. Using fundamental types doesn't really show how let
is different than const
. The difference comes when using it with class instances (reference types):
class CTest
{
var str : String = ""
}
let letTest = CTest()
letTest.str = "test" // OK
letTest.str = "another test" // Still OK
//letTest = CTest() // Error
2. anchorPoint
0, 0
in SpriteKit is the bottom-left corner.
0, 1.0
.
SKSpriteNode
capable of representing our background image and we add it to the scene.anchorPoint
Property
Defines the point in the sprite that corresponds to the node’s position.
Discussion
You specify the value for this property in the unit coordinate space. The default value is (0.5,0.5)
, which means that the sprite is centered on its position.
Import Statement
import SpriteKit
Availability
Available in iOS 7.0 and later.
3. ?和!
var scene: GameScene!
表示GameScence不是一个optional的变量,什么是optional,就是这个变量可以是nil的,也可以不是。
init…
. In order to circumvent this requirement we've added an !
after the type.Swift语言使用var定义变量,但和别的语言不同,Swift里不会自动给变量赋初始值,也就是说变量不会有默认值,所以要求使用变量之前必须要对其初始化。如果在使用变量之前不进行初始化就会报错:
var stringValue : String
//error: variable 'stringValue' used before being initialized
//let hashValue = stringValue.hashValue
// ^
let hashValue = stringValue.hashValue