我這個實驗:爲什麼映射數組本身可以表示出錯?
var orientations1: UIInterfaceOrientationMask = [.portrait, .landscapeRight]
var orientations2: UIInterfaceOrientationMask = [.portrait, .landscapeRight].map { $0 }
orientations1
工作正常,但orientation2
產生以下錯誤:
Type of expression is ambiguous without more context
UIInterfaceOrientationMask
間接符合ExpressibleByArrayLiteral
協議。 .map { $0 }
怎麼可能改變數組的內容,我應該怎麼做才能使它工作?
UPDATE
好了,這裏就是我想要做的事。我正在學習Swift,並希望在運行時改變設備方向。
我有4個交換機:
@IBOutlet weak var switchPortrait: UISwitch!
@IBOutlet weak var switchLandscapeRight: UISwitch!
@IBOutlet weak var switchPortraitUpsideDown: UISwitch!
@IBOutlet weak var switchLandscapeLeft: UISwitch!
var orientationSwitches = [UISwitch]()
var orientations: UIInterfaceOrientationMask = [.portrait, .landscapeRight, .landscapeLeft, .portrait]
在viewDidLoad()
方法,我這樣做:
switchPortrait.tag = Int(UIInterfaceOrientationMask.portrait.rawValue)
switchLandscapeRight.tag = Int(UIInterfaceOrientationMask.landscapeRight.rawValue)
switchPortraitUpsideDown.tag = Int(UIInterfaceOrientationMask.portraitUpsideDown.rawValue)
switchLandscapeLeft.tag = Int(UIInterfaceOrientationMask.landscapeLeft.rawValue)
orientationSwitches = [switchPortrait, switchLandscapeRight, switchPortraitUpsideDown, switchLandscapeLeft]
for switchElement in orientationSwitches {
switchElement.isOn = orientations.contains(UIInterfaceOrientationMask(rawValue: UInt(switchElement.tag)))
}
所以現在每次切換UI元素都有標記設置爲合適的方向面具的原始值。此外,根據初始狀態orientations
,每個開關都打開或關閉。
在開關動作,我試圖更新orientations
這樣的:
@IBAction func orientationSwitched(_ sender: UISwitch) {
orientations = orientationSwitches.filter({ $0.isOn }).map({ UIInterfaceOrientationMask(rawValue: UInt($0.tag)) }) // doesn't work
}
但它不工作。而我supportedInterfaceOrientations
看起來簡直像這樣:
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return orientations
}
我能夠通過每個UI開關組件insert()
的方法來做到這一點,但我想學習,如果能在更優雅的方式來完成,通過映射。
'UIInterfaceOrientationMask'是* OptionSet *,而不是*數組*。所以,即使你可以用數組字面值初始化它,你也不能爲它分配一個數組,這是'map'返回的值。 – vacawama
可怕,但作品:'var orientationations2:UIInterfaceOrientationMask = [UIInterfaceOrientationMask.portrait,.landscapeRight] .map {$ 0} .reduce(UIInterfaceOrientationMask()){var result = $ 0; result.insert($ 1);返回結果}' – vacawama
@vacawama,你可以使用'union','UIInterfaceOrientationMask()'可以用'[]'替換。 – OOPer