Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

【はじめてのSwift】基本的な関数の書き方

More than 5 years have passed since last update.

関数の作り方

一番基礎となる形

A.swift
func favoritePlace(placeName: String) -> String {
    return "I like " + placeName + "."
}

println(favoritePlace("Okinawa"))
// "I like Okinawa." と出力

上記関数は以下のような形。

A.swift
func 関数名 (パラメータ: ) -> 返り値の型 {
    return 返り値
}

複数のパラメータを持つ関数

B.swift
func relationship(s1: String, s2: String, relation: String) -> String {
    return s1 + relation + s2
}
B.swift
func 関数名パラメータ1: パラメータ1の型, パラメータ2: パラメータ2の型, パラメータ3: パラメータ3の型) -> 返り値の型 {
    return 返り値
}

このrelationshipという関数は以下のように呼び出す

relationship("Taro", "Hanako", "likes")
// "Taro likes Hanako"と出力

また、可読性を高めるために以下のように関数を書き換えることも可能。

B.swift
func relationship(man s1: String, woman s2: String, relation joiner: String) -> String {
    return s1 + joiner + s2
}

relationship(man: "Taro", woman: "Hanako", relation: "loves")
// "Taro loves Hanako"と返ってくる

さらに、パラメータ名を省略して書くことも可能。

B.swift
func relationship(#man: String, #woman: String, #relation: String) -> String {
    return man + relation + woman
}

このように書くことで可読性を維持したまま、コード量も省略できる。

relationship(man: "Taro", woman: "Hanako", relation: "hates")
// "Taro hates Hanako"と返る
kiiita
Software Engineer / UI Desiner
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away