'var'매개 변수는 더 이상 사용되지 않으며 Swift 3에서 제거됩니다.
좋아. Xcode를 7.3으로 업데이트하면이 경고 메시지가 나타납니다.
'var'매개 변수는 더 이상 사용되지 않으며 Swift 3에서 제거됩니다.
이 함수에서 var를 사용해야 할 때이 문제를 해결하는 방법 :
public func getQuestionList(var language: String) -> NSArray {
if self.data.count > 0 {
if (language.isEmpty) {
language = "NL"
}
return self.data.objectForKey("questionList" + language) as! NSArray
}
return NSArray()
}
새로운 var에 할당하려고 했습니까?
public func getQuestionList(language: String) -> NSArray {
var lang = language
if self.data.count > 0 {
if (lang.isEmpty) {
lang = "NL"
}
return self.data.objectForKey("questionList" + lang) as! NSArray
}
return NSArray()
}
함수 매개 변수에서 Var를 제거하는 것에 대한 논의는 GitHub의이 제출물 내에 완전히 문서화되어 있습니다 : Var 매개 변수 제거
이 문서에서 사람들은 종종 var
매개 변수와 inout
매개 변수를 혼동한다는 것을 알 수 있습니다. var
파라미터는 단순히 함께하면서 파라미터 함수의 문맥 내에서 변경할 수 있음을 의미 inout
파라미터 반환 지점에서 파라미터의 값은 함수 및 발신자의 상황에 내보내는 것이다.
이 문제를 해결하는 올바른 방법 var
은 매개 변수에서 제거 하고 지역 var
변수를 도입하는 것 입니다. 루틴 맨 위에서 매개 변수 값을 해당 변수에 복사하십시오.
함수의 시작 부분에 다음 한 줄을 추가하십시오.
var language = language
나머지 코드는 다음과 같이 변경되지 않은 상태로 유지 될 수 있습니다.
public func getQuestionList(language: String) -> NSArray {
var language = language
if self.data.count > 0 {
if (language.isEmpty) {
language = "NL"
}
return self.data.objectForKey("questionList" + language) as! NSArray
}
return NSArray()
}
많은 사람들이 inout
매개 변수를 제안 하지만 실제로 설계된 것이 아닙니다. 또한 let
상수 또는 문자열 리터럴을 사용 하여 함수를 호출 할 수 없습니다 . 단순히 함수 서명에 기본값을 추가하지 않는 이유는 무엇입니까?
public func getQuestionList(language language: String = "NL") -> NSArray {
if data.count > 0 {
return data.objectForKey("questionList" + language) as! NSArray
} else {
return NSArray()
}
}
getQuestionList
기본 언어를 원할 경우 빈 문자열로 호출하지 말고 매개 변수를 생략하십시오.
let list = getQuestionList() // uses the default "NL" language
스위프트 4
public func getQuestionList(language: inout String) -> NSArray {
if self.data.count > 0 {
if (language.isEmpty) {
language = "NL"
}
return self.data.objectForKey("questionList" + language) as! NSArray
}
return NSArray()
}
getQuestionList(language: &someString)
In some cases, as I have experienced (with more complex setups involving arrays), creating a new property within the method and mutating that property may not always work. Not to mention, you're cluttering the method instead of simply appending inout
to a parameter and &
to its argument, which is what this syntax was created for.
public func getQuestionList(language: inout String) -> NSArray {
if self.data.count > 0 {
if (language.isEmpty) {
language = "NL"
}
return self.data.objectForKey("questionList" + language) as! NSArray
}
return NSArray()
}
I think @Harris and @garanda answers are the best approach.
Anyway in your case, there isn't need of a var, you can do:
public func getQuestionList(language: String) -> NSArray {
if self.data.count > 0 {
return self.data.objectForKey("questionList" + (language.isEmpty ? "NL" : language)) as! NSArray
}
return NSArray()
}
In-Out Parameters
Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.
You write an in-out parameter by placing the inout keyword right before a parameter’s type. An in-out parameter has a value that is passed in to the function, is modified by the function, and is passed back out of the function to replace the original value. For a detailed discussion of the behavior of in-out parameters and associated compiler optimizations, see In-Out Parameters.
You can only pass a variable as the argument for an in-out parameter. You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified. You place an ampersand (&) directly before a variable’s name when you pass it as an argument to an in-out parameter, to indicate that it can be modified by the function.
NOTE
In-out parameters cannot have default values, and variadic parameters cannot be marked as inout.
Here’s an example of a function called swapTwoInts(::), which has two in-out integer parameters called a and b:
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
The swapTwoInts(::) function simply swaps the value of b into a, and the value of a into b. The function performs this swap by storing the value of a in a temporary constant called temporaryA, assigning the value of b to a, and then assigning temporaryA to b.
You can call the swapTwoInts(::) function with two variables of type Int to swap their values. Note that the names of someInt and anotherInt are prefixed with an ampersand when they are passed to the swapTwoInts(::) function:
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// Prints "someInt is now 107, and anotherInt is now 3"
The example above shows that the original values of someInt and anotherInt are modified by the swapTwoInts(::) function, even though they were originally defined outside of the function.
NOTE
In-out parameters are not the same as returning a value from a function. The swapTwoInts example above does not define a return type or return a value, but it still modifies the values of someInt and anotherInt. In-out parameters are an alternative way for a function to have an effect outside of the scope of its function body.
Here is another idea. My use case was to pass around a string array to append to it, for which the array must be passed in mutably. I did not want to have state in my class for this either. So I made a class that holds the array and pass that. Depending on your use case it may seem silly to have a class that holds just that one variable.
private class StringBuilder {
var buffer: [String] = []
func append(_ str: String) {
buffer.append(str)
}
func toString() -> String {
return buffer.joined()
}
}
I only use append
and joined
methods on the array so it was easy to change the type with minimal other changes to my code.
Some example usage:
private func writeMap(map: LevelMap, url: URL) -> Bool {
let buffer = StringBuilder()
if !writeHeader(map: map, buffer: buffer) {
return false
}
if !writeFloors(map: map, buffer: buffer) {
return false
}
let content = buffer.toString()
do {
try content.write(to: url, atomically: true, encoding: .utf8)
return true
} catch {}
return false
}
private func writeHeader(map: LevelMap, buffer: StringBuilder) -> Bool {
buffer.append("something here ...\n")
return true
}
'Programing' 카테고리의 다른 글
데이터 프레임의 변수가 많은 수식을 간결하게 작성하는 방법은 무엇입니까? (0) | 2020.07.25 |
---|---|
C #에서 IsNullOrEmpty와 IsNullOrWhiteSpace의 차이점 (0) | 2020.07.25 |
Ioc / DI-응용 프로그램 진입 점에서 모든 레이어 / 어셈블리를 참조해야하는 이유는 무엇입니까? (0) | 2020.07.25 |
awk / sed로 여러 번 나타날 수있는 두 마커 패턴 사이에서 선을 선택하는 방법 (0) | 2020.07.25 |
Order By가있는 SQL Group By (0) | 2020.07.25 |