Swift Function argument All In One
Swift Function argument All In One
-
外部参数
a single unnamed parameter
https://docs.swift.org/swift-book/LanguageGuide/Functions.html#ID160
Swift Methods argument All In One
https://docs.swift.org/swift-book/LanguageGuide/Methods.html
Methods are functions that are associated with a particular type.
方法是与特定类型相关联的函数。
function arguments / methods arguments
import Foundation // import SwiftUI // error: no such module 'SwiftUI' // print(Hello World) // _ 外部参数名称,可以省略不写 ✅ func test(_ num: Int) -> Int { print(num); return num; } test(333); // test(num: 333); // extraneous 无关的 // ❌ error: extraneous argument label 'num:' in call // 默认外部参数名称与内部参数一致,不可以省略不写 ✅ func test2(num: Int) -> Int { print(num); return num; } test2(num: 666); // test2(666); // ❌ error: missing argument label 'num:' in call // 指定外部参数名称,不可以省略不写 ✅ func test3(int num: Int) -> Int { print(num); return num; } test3(int: 999); // test3(num: 999); // ❌ error: incorrect argument label in call (have 'num:', expected 'int:')
import Foundation func test(_ num: Int) -> Int { print(num = \(num)); // num = 333 print(num); return num; } test(333);
errors
Global 'var' declaration requires an initializer expression or an explicitly stated getter
Unnamed parameters must be written with the empty name '_'
// function // 命名参数 func getColors(colors: [Color]) -> LinearGradient { return LinearGradient(gradient: Gradient(colors: colors), startPoint: .leading, endPoint: .trailing) } // 未命名参数 ✅,_ 开头 func getColors2(_ colors: [Color]) -> LinearGradient { return LinearGradient(gradient: Gradient(colors: colors), startPoint: .leading, endPoint: .trailing) // '_' can only appear in a pattern or on the left side of an assignment // Unnamed parameters must be written with the empty name '_' }
// 命名参数,必须要写参数名称 `colors:` .background(getColors(colors: card.gradientColors)) // 未命名参数,不需要写参数名称 ✅ .background(getColors2(card.gradientColors))
docs
struct LevelTracker { static var highestUnlockedLevel = 1 var currentLevel = 1 static func unlock(_ level: Int) { if level > highestUnlockedLevel { highestUnlockedLevel = level } } static func isUnlocked(_ level: Int) -> Bool { return level <= highestUnlockedLevel } @discardableResult mutating func advance(to level: Int) -> Bool { if LevelTracker.isUnlocked(level) { currentLevel = level return true } else { return false } } }
https://docs.swift.org/swift-book/LanguageGuide/Methods.html
refs
http://online.swiftplayground.run/
https://www.cnblogs.com/xgqfrms/p/16255693.html
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载