我正在使用带引用的foreach循环,即:Data.ref.authUser(textFieldLoginEmail.text, password: textFieldLoginPassword.text, withCompletionBlock: { error, authData in
if error != nil {
var msg = ""
if let errorCode = FAuthenticationError(rawValue: error.code) {
switch (errorCode) {
case .UserDoesNotExist:
msg = "Invalid user name"
case .InvalidEmail:
msg = "Invalid email"
case .InvalidPassword:
msg = "Invalid password"
case .NetworkError:
msg = "we're sorry, network error has occurred, please login from the settings menu later"
default:
msg = "we're sorry, we encountered an error, please try again"
}
let alert = UIAlertController(title: "User Authentication error",
message: msg,
preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK",
style: .Default) { (action: UIAlertAction!) -> Void in
if errorCode == .NetworkError {
self.performSegueWithIdentifier("ToMenuSegue", sender: self)
}
self.textFieldLoginPassword.text = ""
self.view.endEditing(true)
}
alert.addAction(OKAction)
self.presentViewController(alert, animated: true, completion: nil)
}
} else {
// Logged in
self.performSegueWithIdentifier("ToMenuSegue", sender: self)
}
})
现在当我在foreach($elements as &$item)
之后使用var_dump($elements);
时,最后一个元素的前面总是有一个foreach()
个字符的变量类型&
,{ {1}},&string
等。)
示例输出:
&array
为什么这有什么功能/影响呢?
答案 0 :(得分:2)
这是地址指针。您可以unset($item)
来避免这种情况。
您的问题的答案:
<强> 1。这是为什么 :
您可以在manual
中找到该引用警告 $ value的引用和最后一个数组元素保持均匀 在foreach循环之后。建议通过unset()来销毁它。
当你在foreach循环中使用引用时会出现这种情况。引用位于最后一个数组元素。
<强> 2。它有什么功能/影响
考虑这种情况:
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
}
print_r($arr);
foreach ($arr as $value) {
}
print_r($arr);
您的输出将是:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 3 <---
)
如果您使用unset
:
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
}
print_r($arr);
unset($value); <---
foreach ($arr as $value) {
}
print_r($arr);
结果将是:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4 <---
)