Writing Method

Howe Wu
2 min readJun 22, 2022

這次的目標是要做出隨機生成的 1~100 其中一個數字作為 taget value,同時也要增加無限重新啟動新的回合的功能,會使用自己寫一個 Method 或講 Function 也行?。

首先要先增加一個 Instance variable,它是用來存取 target value 用的,而玩家要針對每次的 target value 顯示的數字用 slider 去滑猜測在 slider 上最接近的 target value 數字。

在最上方做 instance variable 的地方鍵入
var targetValue: Int = 0

接著老師說
Now inside of viewDidLoad, remember this is called when the ViewController first starts up. And it’s good place to initialize any values that you want to initialize.
So we want to initialize the targetValue to a random number.
So we’ll say targetValue equals. The way you make a random number, and this is new in Swift 4.2 is you say Int dot random in.
targetValue = Int.random(in: <#T##ClosedRange<Int>#>)

And it asks you to put a closed range.
You’ll learn more about ranges later in this course but for now it’s very simple.

targetValue = Int.random(in: 1…100)
意思就是隨機生成 1~100 的整數

接著先將此串隨機生成的數字也放進會 popup 出來的字串裡面,原本的為
let message = “The value of the slider is now \(currentValue)”,加上的為
let message = “The value of the slider is now \(currentValue) \nRandom Values is \(targetValue)”,\n ← 這個表示往下一行的意思。

目前這個樣子 targetValue 只會生成一次的隨機數字,然後就只停在那個數字了,這樣跟原本想要的每次都是不同的隨機數字結果不同,所以就開始介紹本堂課要講解的功能 Method。

老師先是講解了目前 Bulleye 接下來應該要怎麼運作如下:
Each guess is a round
When user makes a guess
•Calculate points & add to total
•Increment round number
•Reset slider
•Generate new random number

製作一個 Method 基本它長這樣
func 這裡是這個func的名字() {code 則是打在這裡面},比如以下說這樣
func sayHello(){ print(“Hello”)}

而那個 () 裡面則是放參數用,詳細的 Method 我覺得可以參考以下兩個地方的講解
函式 & Hacking the Swift

然後開始製作 Method
func startRound // Method 的名字 (){
targetValue = Int.random(in: 1…100) // 將 viewDidLoad 上的這串拿過來
currentValue = 50 //這上下兩串的用意為讓 slider 的 Thumb 回到 50
slider.value = Float(currentValue) }// slider 本身的數值是 Float 所以要跟它一樣。

接著老師解釋一些 Method 的運作等等的,有些是我有點不解的

Sometimes you may see method calls written like this.

self.startNewRound()

That does the exact same thing as just start new round without the self dot in front. ( 那到底加 self 要幹嘛🙂?)

Remember how I said that the viewController sends messages to itself, well that’s exactly what self means.

To call a method on an object you’d normally write something in this format.

The Format
receiver.methodName(parameters)

An Example
alert.addAction(action)

The receiver is the object you’re sending the message to.
If you’re sending the message to yourself then the receiver is self.

But you can leave out the self keyword in most cases.
Actually you’ve called several methods like this in your app already.
Such as when you call the addAction method on the alert controller.

--

--

Howe Wu
0 Followers

一介調光師正努力轉生成 iOS 工程師