repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
talentsparkio/AutoLayout
AutoLayout/ViewController.swift
1
2036
// // ViewController.swift // AutoLayout // // Created by Nick Chen on 8/6/15. // Copyright © 2015 TalentSpark. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let contentView = UIView() contentView.backgroundColor = UIColor.grayColor() view = contentView let centerView = UIView() centerView.translatesAutoresizingMaskIntoConstraints = false centerView.backgroundColor = UIColor.blackColor() view.addSubview(centerView) // Half of parent width let halfWidth = centerView.widthAnchor.constraintEqualToAnchor(view.widthAnchor, multiplier: 0.5) // Half of parent height let halfHeight = centerView.heightAnchor.constraintEqualToAnchor(view.heightAnchor, multiplier: 0.5) // Center horizontally let centerX = centerView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor) // Center vertically let centerY = centerView.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor) let redView = UIView() redView.translatesAutoresizingMaskIntoConstraints = false redView.backgroundColor = UIColor.redColor() centerView.addSubview(redView) // 10% of parent width let redWidth = redView.widthAnchor.constraintEqualToAnchor(centerView.widthAnchor, multiplier: 0.1) // 10% of parent height let redHeight = redView.heightAnchor.constraintEqualToAnchor(centerView.heightAnchor, multiplier: 0.1) let redX = centerView.leftAnchor.constraintEqualToAnchor(redView.leftAnchor) let redY = centerView.topAnchor.constraintEqualToAnchor(redView.topAnchor) NSLayoutConstraint.activateConstraints([halfWidth, halfHeight, centerX, centerY, redWidth, redHeight, redX, redY]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
bsd-3-clause
1b6ac7d86d599c7498b312a7f2ea89bd
32.916667
122
0.6914
5.70028
false
false
false
false
OSzhou/MyTestDemo
17_SwiftTestCode/TestCode/OtherPro/WBAlertBaseView.swift
1
4809
// // WBAlertBaseView.swift // ACN_Wallet // // Created by Zhouheng on 2020/5/11. // Copyright © 2020 TTC. All rights reserved. // import UIKit class WBAlertBaseView: UIView { var closeClick:(() -> ())? /// 此刻弹框是否正在展示中 static private(set) var showing: Bool = false required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect = UIScreen.main.bounds) { super.init(frame: frame) setupSubviews() } private func setupSubviews() { self.backgroundColor = UIColor.black.withAlphaComponent(0.5) addSubview(contentView) contentView.addSubview(titleLabel) contentView.addSubview(customView) contentView.addSubview(comfirmButton) contentView.addSubview(cancelButton) titleLabel.snp.makeConstraints { (make) in make.left.equalTo(24) make.right.equalTo(-8) make.top.equalTo(20) } customView.snp.makeConstraints { (make) in make.centerX.equalTo(contentView) make.top.equalTo(titleLabel.snp.bottom).offset(8) make.bottom.equalTo(comfirmButton.snp.top).offset(-8) make.height.equalTo(100) make.width.equalTo(screenWidth - 80) } comfirmButton.snp.makeConstraints { (make) in make.width.equalTo(75) make.height.equalTo(36) make.right.bottom.equalTo(-8) } cancelButton.snp.makeConstraints { (make) in make.width.equalTo(75) make.height.equalTo(36) make.right.equalTo(comfirmButton.snp.left).offset(-8) make.bottom.equalTo(-8) } contentView.snp.makeConstraints { (make) in make.left.right.equalTo(customView) make.center.equalTo(self) } } /// MARK: --- action @objc func buttonClick(_ sender: UIButton) { } @objc private func cancelButtonClick(_ sender: UIButton) { dismiss(completion: { self.cancel() }) } func cancel() { self.closeClick?() } @discardableResult func show(_ superview: UIView? = nil) -> Bool { guard !WBAlertBaseView.showing else { return false } guard let superView = superview ?? UIApplication.shared.windows.first else { return false } alpha = 0 superView.addSubview(self) WBAlertBaseView.showing = true UIView.animate(withDuration: 0.25) { self.alpha = 1 } return true } func dismiss(animated: Bool = true, completion: (() -> Void)? = nil) { let finish = { [weak self] (finish: Bool) in self?.removeFromSuperview() WBAlertBaseView.showing = false completion?() } if animated { UIView.animate(withDuration: 0.25, animations: { self.alpha = 0 }, completion: finish) } else { finish(true) } } /// MARK: --- lazy loading lazy var contentView: UIView = { let view = UIView() view.backgroundColor = .white view.layer.cornerRadius = 2 // shadowCode view.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.26).cgColor view.layer.shadowOffset = CGSize(width: 0, height: 12) view.layer.shadowOpacity = 1 view.layer.shadowRadius = 24 return view }() lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 20) label.textColor = UIColor.gray label.adjustsFontSizeToFitWidth = true return label }() lazy var customView: UIView = { let view = UIView() return view }() lazy var comfirmButton: UIButton = { let button = UIButton(type: .custom) button.setTitleColor(UIColor.black, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.setTitle("确认", for: .normal) button.addTarget(self, action: #selector(buttonClick(_:)), for: .touchUpInside) return button }() lazy var cancelButton: UIButton = { let button = UIButton(type: .custom) button.setTitleColor(UIColor.black, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.setTitle("取消", for: .normal) button.addTarget(self, action: #selector(cancelButtonClick(_:)), for: .touchUpInside) return button }() }
apache-2.0
4bcd44f52d66773f64a8146eef89d1ea
28.134146
99
0.565509
4.603083
false
false
false
false
nextcloud/ios
iOSClient/Activity/NCActivityTableViewCell.swift
1
11277
// // NCActivityCollectionViewCell.swift // Nextcloud // // Created by Henrik Storch on 17/01/2019. // Copyright © 2021. All rights reserved. // // Author Henrik Storch <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import Foundation import NextcloudKit import FloatingPanel import JGProgressHUD class NCActivityCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! var fileId = "" override func awakeFromNib() { super.awakeFromNib() } } class NCActivityTableViewCell: UITableViewCell, NCCellProtocol { private let appDelegate = UIApplication.shared.delegate as! AppDelegate @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var icon: UIImageView! @IBOutlet weak var avatar: UIImageView! @IBOutlet weak var subject: UILabel! @IBOutlet weak var subjectTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint! private var user: String = "" var idActivity: Int = 0 var activityPreviews: [tableActivityPreview] = [] var didSelectItemEnable: Bool = true var viewController: UIViewController? var fileAvatarImageView: UIImageView? { get { return avatar } } var fileUser: String? { get { return user } set { user = newValue ?? "" } } override func awakeFromNib() { super.awakeFromNib() collectionView.delegate = self collectionView.dataSource = self let avatarRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapAvatarImage)) avatar.addGestureRecognizer(avatarRecognizer) } @objc func tapAvatarImage() { guard let fileUser = fileUser else { return } viewController?.showProfileMenu(userId: fileUser) } } // MARK: - Collection View extension NCActivityTableViewCell: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // Select not permitted if !didSelectItemEnable { return } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as? NCActivityCollectionViewCell let activityPreview = activityPreviews[indexPath.row] if activityPreview.view == "trashbin" { var responder: UIResponder? = collectionView while !(responder is UIViewController) { responder = responder?.next if responder == nil { break } } if (responder as? UIViewController)!.navigationController != nil { if let viewController = UIStoryboard(name: "NCTrash", bundle: nil).instantiateInitialViewController() as? NCTrash { if let result = NCManageDatabase.shared.getTrashItem(fileId: String(activityPreview.fileId), account: activityPreview.account) { viewController.blinkFileId = result.fileId viewController.trashPath = result.filePath (responder as? UIViewController)!.navigationController?.pushViewController(viewController, animated: true) } else { let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_trash_file_not_found_") NCContentPresenter.shared.showError(error: error) } } } return } if activityPreview.view == NCGlobal.shared.appName && activityPreview.mimeType != "dir" { guard let activitySubjectRich = NCManageDatabase.shared.getActivitySubjectRich(account: activityPreview.account, idActivity: activityPreview.idActivity, id: String(activityPreview.fileId)) else { return } if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "fileId == %@", activitySubjectRich.id)) { if let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) { do { let attr = try FileManager.default.attributesOfItem(atPath: filePath) let fileSize = attr[FileAttributeKey.size] as! UInt64 if fileSize > 0 { if let viewController = self.viewController { NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: cell?.imageView.image) } return } } catch { print("Error: \(error)") } } } let hud = JGProgressHUD() hud.indicatorView = JGProgressHUDRingIndicatorView() if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView { indicatorView.ringWidth = 1.5 } guard let view = appDelegate.window?.rootViewController?.view else { return } hud.show(in: view) NextcloudKit.shared.getFileFromFileId(fileId: String(activityPreview.fileId)) { account, file, data, error in if let file = file { let metadata = NCManageDatabase.shared.convertNCFileToMetadata(file, isEncrypted: file.e2eEncrypted, account: account) NCManageDatabase.shared.addMetadata(metadata) let serverUrlFileName = metadata.serverUrl + "/" + metadata.fileName let fileNameLocalPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)! NextcloudKit.shared.download(serverUrlFileName: serverUrlFileName, fileNameLocalPath: fileNameLocalPath, requestHandler: { _ in }, taskHandler: { _ in }, progressHandler: { progress in hud.progress = Float(progress.fractionCompleted) }) { account, _, _, _, _, _, error in hud.dismiss() if account == self.appDelegate.account && error == .success { NCManageDatabase.shared.addLocalFile(metadata: metadata) if let viewController = self.viewController { NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: cell?.imageView.image) } } } } else if error != .success { hud.dismiss() NCContentPresenter.shared.showError(error: error) } } } } } extension NCActivityTableViewCell: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let results = activityPreviews.unique { $0.fileId } return results.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: NCActivityCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! NCActivityCollectionViewCell cell.imageView.image = nil let activityPreview = activityPreviews[indexPath.row] let fileId = String(activityPreview.fileId) // Trashbin if activityPreview.view == "trashbin" { let source = activityPreview.source NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: source, fileName: nil, width: 100, rewrite: false, account: appDelegate.account) { imageNamePath in if imageNamePath != nil { if let image = UIImage(contentsOfFile: imageNamePath!) { cell.imageView.image = image } } else { cell.imageView.image = UIImage(named: "file_photo") } } } else { if activityPreview.isMimeTypeIcon { let source = activityPreview.source NCUtility.shared.convertSVGtoPNGWriteToUserData(svgUrlString: source, fileName: nil, width: 100, rewrite: false, account: appDelegate.account) { imageNamePath in if imageNamePath != nil { if let image = UIImage(contentsOfFile: imageNamePath!) { cell.imageView.image = image } } else { cell.imageView.image = UIImage(named: "file_photo") } } } else { if let activitySubjectRich = NCManageDatabase.shared.getActivitySubjectRich(account: activityPreview.account, idActivity: idActivity, id: fileId) { let fileNamePath = CCUtility.getDirectoryUserData() + "/" + activitySubjectRich.name if FileManager.default.fileExists(atPath: fileNamePath) { if let image = UIImage(contentsOfFile: fileNamePath) { cell.imageView.image = image } } else { NCOperationQueue.shared.downloadThumbnailActivity(fileNamePathOrFileId: activityPreview.source, fileNamePreviewLocalPath: fileNamePath, fileId: fileId, cell: cell, collectionView: collectionView) } } } } return cell } } extension NCActivityTableViewCell: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 50, height: 50) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 20 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0) } }
gpl-3.0
73dfecb022d684b50eee69f3180430bb
40.455882
219
0.621054
5.674887
false
false
false
false
werner-freytag/DockTime
Swift Extensions/NSBezierPath+Extension.swift
1
2570
// The MIT License // // Copyright 2012-2021 Werner Freytag // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import AppKit.NSBezierPath import Foundation public extension NSBezierPath { func addLine(to: CGPoint) { line(to: to) } var cgPath: CGPath { let path = CGMutablePath() var points = [CGPoint](repeating: .zero, count: 3) for i in 0 ..< elementCount { let type = element(at: i, associatedPoints: &points) switch type { case .moveTo: path.move(to: points[0]) case .lineTo: path.addLine(to: points[0]) case .curveTo: path.addCurve(to: points[2], control1: points[0], control2: points[1]) case .closePath: path.closeSubpath() @unknown default: fatalError() } } return path } var usesEvenOddFillRule: Bool { get { return windingRule == .evenOdd } set { windingRule = newValue ? .evenOdd : .nonZero } } func apply(_ transform: CGAffineTransform) { self.transform(using: AffineTransform(transform: transform)) } convenience init(roundedRect rect: CGRect, cornerRadius radius: CGFloat) { self.init(roundedRect: rect, xRadius: radius, yRadius: radius) } } private extension AffineTransform { init(transform: CGAffineTransform) { self.init(m11: transform.a, m12: transform.b, m21: transform.c, m22: transform.a, tX: transform.tx, tY: transform.ty) } }
mit
f82d2cfc5c44f1750a9c981adeeaebfd
35.714286
125
0.667704
4.408233
false
false
false
false
cplaverty/KeitaiWaniKani
AlliCrab/Util/SubjectCell.swift
1
1233
// // SubjectCell.swift // AlliCrab // // Copyright © 2019 Chris Laverty. All rights reserved. // import UIKit import WaniKaniKit protocol SubjectCell { var characterView: SubjectCharacterView! { get } var primaryReadingLabel: UILabel! { get } var primaryMeaningLabel: UILabel! { get } var subjectID: Int { get } func setSubject(_ subject: Subject, id: Int) } extension SubjectCell { var subjectID: Int { return characterView.subjectID } } extension SubjectCell where Self: UIView { func setSubject(_ subject: Subject, id: Int) { characterView.setSubject(subject, id: id) backgroundColor = subject.subjectType.backgroundColor setText(subject.primaryReading, for: primaryReadingLabel) setText(subject.primaryMeaning, for: primaryMeaningLabel) // Fix for self-sizing cells on iOS 12 updateConstraintsIfNeeded() } private func setText(_ text: String?, for label: UILabel?) { guard let label = label else { return } if let text = text { label.text = text label.isHidden = false } else { label.isHidden = true } } }
mit
634295331f65fbaff0624a63b5805362
24.142857
65
0.624188
4.631579
false
false
false
false
xmartlabs/XLSwiftKit
Sources/UIColor.swift
1
1799
// // UIColor.swift // XLFoundationSwiftKit // // Created by mathias Claassen on 24/11/15. // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex: Int) { self.init(red: (netHex >> 16) & 0xff, green: (netHex >> 8) & 0xff, blue: netHex & 0xff) } }
mit
b94dabcba449b016d2c5985f7723c301
41.833333
116
0.702613
4.006682
false
false
false
false
pinterest/tulsi
src/TulsiGenerator/BazelBuildSettingsFeatures.swift
2
3748
// Copyright 2017 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Returns the configuration flags required to build a Bazel target and all of its dependencies /// with the specified PlatformType and AppleCPU. /// /// - Every platform has the --apple_platform_type flag set /// - macOS and iOS use the base --cpu flag, while tvOS and watchOS use the --tvos_cpus and /// --watchos_cpus respectively /// - iOS also sets the --watchos_cpus flag (as it can contain a watchOS app embedded) extension PlatformConfiguration { public var bazelFlags: [String] { var flags = ["--apple_platform_type=\(platform.bazelPlatform)"] let physicalWatchCPUs = "\(CPU.armv7k.rawValue),\(CPU.arm64_32.rawValue)" switch platform { case .ios, .macos: flags.append("--cpu=\(platform.bazelCPUPlatform)_\(cpu.rawValue)") case .tvos: flags.append("--\(platform.bazelCPUPlatform)_cpus=\(cpu.rawValue)") case .watchos: if (cpu == .armv7k || cpu == .arm64_32) { // Xcode doesn't provide a way to determine the architecture of a watch // so target both watchOS cpus when building for a physical watch. flags.append("--\(platform.bazelCPUPlatform)_cpus=\(physicalWatchCPUs)") } else { flags.append("--\(platform.bazelCPUPlatform)_cpus=\(cpu.watchCPU.rawValue)") } } if case .ios = platform { if cpu == .arm64 || cpu == .arm64e { // Xcode doesn't provide a way to determine the architecture of a paired // watch so target both watchOS cpus when building for physical iOS, // otherwise we might unintentionally install a watch app with the wrong // architecture. Only 64-bit iOS devices support the Apple Watch Series // 4 so we only need to apply the flag to the 64bit iOS CPUs. flags.append("--\(PlatformType.watchos.bazelCPUPlatform)_cpus=\(physicalWatchCPUs)") } else { flags.append("--\(PlatformType.watchos.bazelCPUPlatform)_cpus=\(cpu.watchCPU.rawValue)") } } return flags } } public class BazelBuildSettingsFeatures { public static func enabledFeatures(options: TulsiOptionSet) -> Set<BazelSettingFeature> { // A normalized path for -fdebug-prefix-map exists for keeping all debug information as built by // Clang consistent for the sake of caching within a distributed build system. // // This is handled through a wrapped_clang feature flag via the CROSSTOOL. // // The use of this flag does not affect any sources built by swiftc. At present time, all Swift // compiled sources will be built with uncacheable, absolute paths, as until Xcode 10.2, the // Swift compiler did not present an easy means of similarly normalizing all debug information. // Unfortunately, this still has some slight issues (which may be worked around via changes to // wrapped_clang). var features: Set<BazelSettingFeature> = [.DebugPathNormalization] if options[.SwiftForcesdSYMs].commonValueAsBool ?? false { features.insert(.SwiftForcesdSYMs) } if options[.TreeArtifactOutputs].commonValueAsBool ?? true { features.insert(.TreeArtifactOutputs) } return features } }
apache-2.0
f0ee9b07eb58aeff4d446b44ac6c5609
45.85
100
0.69984
4.393904
false
false
false
false
koehlermichael/focus
Blockzilla/URIFixup.swift
1
1477
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation class URIFixup { static func getURL(entry: String) -> URL? { let trimmed = entry.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) guard let escaped = trimmed.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlAllowed) else { return nil } // Check if the URL includes a scheme. This will handle // all valid requests starting with "http://", "about:", etc. if let url = URL(string: entry), url.scheme != nil { return url } // If there's no scheme, we're going to prepend "http://". First, // make sure there's at least one "." in the host. This means // we'll allow single-word searches (e.g., "foo") at the expense // of breaking single-word hosts without a scheme (e.g., "localhost"). if trimmed.range(of: ".") == nil { return nil } if trimmed.range(of: " ") != nil { return nil } // If there is a ".", prepend "http://" and try again. Since this // is strictly an "http://" URL, we also require a host. if let url = URL(string: "http://\(escaped)"), url.host != nil { return url } return nil } }
mpl-2.0
842aef4837b959818202ecce2c5975c3
35.925
112
0.586324
4.344118
false
false
false
false
akio0911/til
20201219/TextEditor/TextEditor/EditorModel.swift
1
798
// // EditorModel.swift // TextEditor // // Created by akio0911 on 2020/12/19. // import Foundation protocol EditorModelDelegate: AnyObject { func changeTextView(text: String) } final class EditorModel { weak var delegate: EditorModelDelegate? private var currentText = "" private var textHistories: [String] = [] func textDidChange(text: String) { textHistories.append(currentText) currentText = text } func clear() { textHistories.append(currentText) currentText = "" delegate?.changeTextView(text: "") } func undo() { guard !textHistories.isEmpty else { return } let last = textHistories.removeLast() currentText = last delegate?.changeTextView(text: last) } }
mit
b5ce620cd36eb59fbeac066a847a7b27
20.567568
52
0.631579
4.360656
false
false
false
false
as767439266/DouYuZG
DouYuZG/DouYuZG/Classes/Main/View/PageTitleView.swift
1
6705
// // PageTitleView.swift // DouYuZG // // Created by 蒋学超 on 16/9/23. // Copyright © 2016年 JiangXC. All rights reserved. // import UIKit //MARK:-定义协议 protocol PageTitleViewDelegate :class{ func pageTitleView(titleView : PageTitleView, selectedIndex index : Int) } // MARK:- 定义常量 private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) class PageTitleView: UIView { //懒加载 //懒加载一个lable 数组 lazy var titleLabels : [UILabel] = [UILabel]() lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() //定义属性 var currentIndex : Int = 0 var titles :[String] weak var delegate : PageTitleViewDelegate? //MARK : 自定义构造函数 init(frame: CGRect,titles:[String]) { self.titles = titles super.init(frame: frame) print(frame) //设置UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK- 设置UI界面 extension PageTitleView{ func setupUI(){ //1 添加ScrollView addSubview(scrollView) scrollView.frame = bounds //2 添加title 的label setupTitleLables() // 3.设置底线和滚动的滑块 setupBottomLineAndScrollLine() } private func setupTitleLables() { // 0.确定label的一些frame的值 let labelW : CGFloat = bounds.width / CGFloat(titles.count) let labelH : CGFloat = bounds.height - kScrollLineH let labelY : CGFloat = 0 for (index,title) in titles.enumerated(){ //创建lable let lable = UILabel() //设置lable的属性 lable.text = title lable.tag = index lable.font = UIFont.systemFont(ofSize: 16.0) lable.tintColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) lable.textAlignment = .center //3 设置lable 的frame let labelX : CGFloat = labelW * CGFloat(index) lable.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) //4 将lable 添加到scroolview scrollView.addSubview(lable) titleLabels.append(lable) // 5.给Label添加手势 lable.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action:#selector(PageTitleView.titleLabelClick)) lable.addGestureRecognizer(tapGes) // //5 给 lable 添加手势 // lable.isUserInteractionEnabled = true //// let tapGes = UITapGestureRecognizer(target: self, action:#selector(self.titleLabelClick(_:))) // let tapGes = UITapGestureRecognizer(target: self, action: Selector(("titleLabelClick:"))) // lable.addGestureRecognizer(tapGes) } } private func setupBottomLineAndScrollLine(){ //1 添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) // 2.添加scrollLine // 2.1.获取第一个Label guard let firstLabel = titleLabels.first else { return } firstLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) // 2.2.设置scrollLine的属性 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH) } } //MARK:- 手势事件 extension PageTitleView{ @objc func titleLabelClick(tapGes : UITapGestureRecognizer){ // 0.获取当前Label guard let currentLabel = tapGes.view as? UILabel else { return } // 1.如果是重复点击同一个Title,那么直接返回 if currentLabel.tag == currentIndex { return } // 2.获取之前的Label let oldLabel = titleLabels[currentIndex] // 3.切换文字的颜色 currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) // 4.保存最新Label的下标值 currentIndex = currentLabel.tag // 5.滚动条位置发生改变 let scrollLineX = CGFloat(currentIndex) * scrollLine.frame.width UIView.animate(withDuration: 0.15) { self.scrollLine.frame.origin.x = scrollLineX } // 6.通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } // MARK:- 对外暴露的方法 extension PageTitleView { func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 2.处理滑块的逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) // 3.2.变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex } }
mit
aca34ae408c2a5c9ab2f16856561b145
33.480874
174
0.611252
4.698436
false
false
false
false
neopixl/NPFlipButton
NPButtonFlip/Classes/NPButtonWithFlip/NPButtonWithFilp.swift
1
7057
/* Copyright 2015 NEOPIXL S.A. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit public class NPButtonWithFilp: UIControl { var borderColor: UIColor! var offColor: UIColor! var onColor: UIColor! private var flipButton: NPFlipView! var flipOffImage: UIImage! var flipOnImage: UIImage! var text: String! var textFont: UIFont! private var currentOff = true private var label: UILabel! // MARK: - Init required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initComponents() } override init(frame: CGRect) { super.init(frame: frame) initComponents() } // MARK: - Private methods private func initComponents() { self.label = UILabel() self.flipButton = NPFlipView(frame: CGRect(x: 0, y: 0, width: 32, height: 36)) label.translatesAutoresizingMaskIntoConstraints = false flipButton.translatesAutoresizingMaskIntoConstraints = false self.addSubview(label) self.addSubview(flipButton) let labelCenterYConstraint = NSLayoutConstraint(item:label, attribute:NSLayoutConstraint.Attribute.centerY, relatedBy:NSLayoutConstraint.Relation.equal, toItem:self, attribute:NSLayoutConstraint.Attribute.centerY, multiplier:1, constant:0) self.addConstraint(labelCenterYConstraint) let labelPinLeftBorderConstraint = NSLayoutConstraint(item:label, attribute:NSLayoutConstraint.Attribute.leading, relatedBy:NSLayoutConstraint.Relation.equal, toItem:self, attribute:NSLayoutConstraint.Attribute.leading, multiplier:1, constant:15) self.addConstraint(labelPinLeftBorderConstraint) let flipCenterYConstraint = NSLayoutConstraint(item:flipButton, attribute:NSLayoutConstraint.Attribute.centerY, relatedBy:NSLayoutConstraint.Relation.equal, toItem:self, attribute:NSLayoutConstraint.Attribute.centerY, multiplier:1, constant:2) self.addConstraint(flipCenterYConstraint) let flipPinLeftBorderConstraint = NSLayoutConstraint(item:flipButton, attribute:NSLayoutConstraint.Attribute.trailing, relatedBy:NSLayoutConstraint.Relation.equal, toItem:self, attribute:NSLayoutConstraint.Attribute.trailing, multiplier:1, constant:-10) self.addConstraint(flipPinLeftBorderConstraint) } // MARK: - Public methods public func setParameters(borderColor: UIColor, offColor: UIColor, onColor: UIColor, flipOffImage: UIImage, flipOnImage: UIImage, text: String, textFont: UIFont) { self.borderColor = borderColor self.offColor = offColor self.onColor = onColor self.flipOffImage = flipOffImage self.flipOnImage = flipOnImage self.text = text label.text = self.text self.textFont = textFont label.font = self.textFont label.textColor = self.onColor self.layer.borderColor = self.borderColor.cgColor self.layer.borderWidth = 1 self.layer.cornerRadius = 2 self.backgroundColor = offColor flipButton.setImages(frontImage: flipOnImage, backImage: flipOffImage) flipButton.addTarget(self, action: #selector(flipTouchDown), for: .touchDown) flipButton.addTarget(self, action: #selector(flipTouchUpInside), for: .touchUpInside) flipButton.removeConstraints(flipButton.constraints) let views = ["view": flipButton] //+4 for shadow let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat:"V:[view(\(flipOffImage.size.height+4))]", options: [], metrics: nil, views: views as [String : Any]) flipButton.addConstraints(verticalConstraints) let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[view(\(flipOffImage.size.width))]", options: [], metrics: nil, views: views as [String : Any]) flipButton.addConstraints(horizontalConstraints) } public func setState (on: Bool, animated: Bool) { if(currentOff == on) { if !on { if animated { UIView.animate(withDuration: 0.2, animations: { self.backgroundColor = self.offColor self.label.textColor = self.onColor }) } else { self.backgroundColor = self.offColor self.label.textColor = self.onColor } } else { if animated { UIView.animate(withDuration: 0.2, animations: { self.backgroundColor = self.onColor self.label.textColor = self.offColor }) } else { self.backgroundColor = self.onColor self.label.textColor = self.offColor } } self.flipButton.flip(animated: animated, duration: 0.3, toBack: on, completionBlock: nil) self.currentOff = !on } } public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { didBegin() } private func didBegin() { if self.currentOff { UIView.animate(withDuration: 0.2, animations: { self.backgroundColor = self.onColor self.label.textColor = self.offColor }) } else { UIView.animate(withDuration: 0.2, animations: { self.backgroundColor = self.offColor self.label.textColor = self.onColor }) } self.currentOff = !self.currentOff self.sendActions(for: .touchDown) } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { didEnd() } private func didEnd() { self.flipButton.flip(animated: true, duration: 0.3, completionBlock: nil) self.sendActions(for: .touchUpInside) } @objc internal func flipTouchUpInside() { didEnd() } @objc internal func flipTouchDown() { didBegin() } }
apache-2.0
7a6284d1b1ce4342ba2c497f6ec42e0e
35.189744
183
0.610599
4.807221
false
false
false
false
sschiau/swift-package-manager
Tests/CommandsTests/PackageToolTests.swift
2
27167
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Foundation import Basic @testable import Commands import Xcodeproj import PackageModel import SourceControl import TestSupport import Utility import Workspace @testable import class Workspace.PinsStore final class PackageToolTests: XCTestCase { @discardableResult private func execute(_ args: [String], packagePath: AbsolutePath? = nil, env: [String: String]? = nil) throws -> String { return try SwiftPMProduct.SwiftPackage.execute(args, packagePath: packagePath, env: env).spm_chomp() } func testUsage() throws { XCTAssert(try execute(["--help"]).contains("USAGE: swift package")) } func testSeeAlso() throws { XCTAssert(try execute(["--help"]).contains("SEE ALSO: swift build, swift run, swift test")) } func testVersion() throws { XCTAssert(try execute(["--version"]).contains("Swift Package Manager")) } func testResolve() throws { fixture(name: "DependencyResolution/External/Simple") { prefix in let packageRoot = prefix.appending(component: "Bar") // Check that `resolve` works. _ = try execute(["resolve"], packagePath: packageRoot) let path = try SwiftPMProduct.packagePath(for: "Foo", packageRoot: packageRoot) XCTAssertEqual(GitRepository(path: path).tags, ["1.2.3"]) } } func testUpdate() throws { fixture(name: "DependencyResolution/External/Simple") { prefix in let packageRoot = prefix.appending(component: "Bar") // Perform an initial fetch. _ = try execute(["resolve"], packagePath: packageRoot) var path = try SwiftPMProduct.packagePath(for: "Foo", packageRoot: packageRoot) XCTAssertEqual(GitRepository(path: path).tags, ["1.2.3"]) // Retag the dependency, and update. let repo = GitRepository(path: prefix.appending(component: "Foo")) try repo.tag(name: "1.2.4") _ = try execute(["update"], packagePath: packageRoot) // We shouldn't assume package path will be same after an update so ask again for it. path = try SwiftPMProduct.packagePath(for: "Foo", packageRoot: packageRoot) XCTAssertEqual(GitRepository(path: path).tags, ["1.2.3", "1.2.4"]) } } func testDescribe() throws { fixture(name: "CFamilyTargets/SwiftCMixed") { prefix in let result = try SwiftPMProduct.SwiftPackage.executeProcess(["describe", "--type=json"], packagePath: prefix) let output = try result.utf8Output() let json = try JSON(bytes: ByteString(encodingAsUTF8: output)) XCTAssertEqual(json["name"]?.string, "SwiftCMixed") // Path should be an absolute path. XCTAssert(json["path"]?.string?.hasPrefix("/") == true) // Sort the target. let targets = json["targets"]?.array?.sorted { guard let first = $0["name"], let second = $1["name"] else { return false } return first.stringValue < second.stringValue } XCTAssertEqual(targets?[0]["name"]?.stringValue, "CExec") XCTAssertEqual(targets?[2]["type"]?.stringValue, "library") XCTAssertEqual(targets?[1]["sources"]?.array?.map{$0.stringValue} ?? [], ["main.swift"]) let textOutput = try execute(["describe"], packagePath: prefix) XCTAssert(textOutput.hasPrefix("Name: SwiftCMixed")) XCTAssert(textOutput.contains(" C99name: CExec")) XCTAssert(textOutput.contains(" Name: SeaLib")) XCTAssert(textOutput.contains(" Sources: main.swift")) } } func testDumpPackage() throws { fixture(name: "DependencyResolution/External/Complex") { prefix in let packageRoot = prefix.appending(component: "app") let dumpOutput = try execute(["dump-package"], packagePath: packageRoot) let json = try JSON(bytes: ByteString(encodingAsUTF8: dumpOutput)) guard case let .dictionary(contents) = json else { XCTFail("unexpected result"); return } guard case let .string(name)? = contents["name"] else { XCTFail("unexpected result"); return } XCTAssertEqual(name, "Dealer") } } func testShowDependencies() throws { fixture(name: "DependencyResolution/External/Complex") { prefix in let packageRoot = prefix.appending(component: "app") let textOutput = try SwiftPMProduct.SwiftPackage.executeProcess(["show-dependencies", "--format=text"], packagePath: packageRoot).utf8Output() XCTAssert(textOutput.contains("[email protected]")) let jsonOutput = try SwiftPMProduct.SwiftPackage.executeProcess(["show-dependencies", "--format=json"], packagePath: packageRoot).utf8Output() let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput)) guard case let .dictionary(contents) = json else { XCTFail("unexpected result"); return } guard case let .string(name)? = contents["name"] else { XCTFail("unexpected result"); return } XCTAssertEqual(name, "Dealer") guard case let .string(path)? = contents["path"] else { XCTFail("unexpected result"); return } XCTAssertEqual(resolveSymlinks(AbsolutePath(path)), resolveSymlinks(packageRoot)) } } func testInitEmpty() throws { mktmpdir { tmpPath in let fs = localFileSystem let path = tmpPath.appending(component: "Foo") try fs.createDirectory(path) _ = try execute(["init", "--type", "empty"], packagePath: path) XCTAssert(fs.exists(path.appending(component: "Package.swift"))) XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources")), []) XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Tests")), []) } } func testInitExecutable() throws { mktmpdir { tmpPath in let fs = localFileSystem let path = tmpPath.appending(component: "Foo") try fs.createDirectory(path) _ = try execute(["init", "--type", "executable"], packagePath: path) let manifest = path.appending(component: "Package.swift") let contents = try localFileSystem.readFileContents(manifest).asString! let version = "\(InitPackage.newPackageToolsVersion.major).\(InitPackage.newPackageToolsVersion.minor)" XCTAssertTrue(contents.hasPrefix("// swift-tools-version:\(version)\n")) XCTAssertTrue(fs.exists(manifest)) XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources").appending(component: "Foo")), ["main.swift"]) XCTAssertEqual( try fs.getDirectoryContents(path.appending(component: "Tests")).sorted(), ["FooTests", "LinuxMain.swift"]) } } func testInitLibrary() throws { mktmpdir { tmpPath in let fs = localFileSystem let path = tmpPath.appending(component: "Foo") try fs.createDirectory(path) _ = try execute(["init"], packagePath: path) XCTAssert(fs.exists(path.appending(component: "Package.swift"))) XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources").appending(component: "Foo")), ["Foo.swift"]) XCTAssertEqual( try fs.getDirectoryContents(path.appending(component: "Tests")).sorted(), ["FooTests", "LinuxMain.swift"]) } } func testInitCustomNameExecutable() throws { mktmpdir { tmpPath in let fs = localFileSystem let path = tmpPath.appending(component: "Foo") try fs.createDirectory(path) _ = try execute(["init", "--name", "CustomName", "--type", "executable"], packagePath: path) let manifest = path.appending(component: "Package.swift") let contents = try localFileSystem.readFileContents(manifest).asString! let version = "\(InitPackage.newPackageToolsVersion.major).\(InitPackage.newPackageToolsVersion.minor)" XCTAssertTrue(contents.hasPrefix("// swift-tools-version:\(version)\n")) XCTAssertTrue(fs.exists(manifest)) XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources").appending(component: "CustomName")), ["main.swift"]) XCTAssertEqual( try fs.getDirectoryContents(path.appending(component: "Tests")).sorted(), ["CustomNameTests", "LinuxMain.swift"]) } } func testPackageEditAndUnedit() { fixture(name: "Miscellaneous/PackageEdit") { prefix in let fooPath = prefix.appending(component: "foo") func build() throws -> String { return try SwiftPMProduct.SwiftBuild.execute([], packagePath: fooPath) } // Put bar and baz in edit mode. _ = try SwiftPMProduct.SwiftPackage.execute(["edit", "bar", "--branch", "bugfix"], packagePath: fooPath) _ = try SwiftPMProduct.SwiftPackage.execute(["edit", "baz", "--branch", "bugfix"], packagePath: fooPath) // Path to the executable. let exec = [fooPath.appending(components: ".build", Destination.host.target, "debug", "foo").asString] // We should see it now in packages directory. let editsPath = fooPath.appending(components: "Packages", "bar") XCTAssert(isDirectory(editsPath)) let bazEditsPath = fooPath.appending(components: "Packages", "baz") XCTAssert(isDirectory(bazEditsPath)) // Removing baz externally should just emit an warning and not a build failure. try localFileSystem.removeFileTree(bazEditsPath) // Do a modification in bar and build. try localFileSystem.writeFileContents(editsPath.appending(components: "Sources", "bar.swift"), bytes: "public let theValue = 88888\n") let buildOutput = try build() XCTAssert(buildOutput.contains("dependency 'baz' was being edited but is missing; falling back to original checkout")) // We should be able to see that modification now. XCTAssertEqual(try Process.checkNonZeroExit(arguments: exec), "88888\n") // The branch of edited package should be the one we provided when putting it in edit mode. let editsRepo = GitRepository(path: editsPath) XCTAssertEqual(try editsRepo.currentBranch(), "bugfix") // It shouldn't be possible to unedit right now because of uncommited changes. do { _ = try SwiftPMProduct.SwiftPackage.execute(["unedit", "bar"], packagePath: fooPath) XCTFail("Unexpected unedit success") } catch {} try editsRepo.stageEverything() try editsRepo.commit() // It shouldn't be possible to unedit right now because of unpushed changes. do { _ = try SwiftPMProduct.SwiftPackage.execute(["unedit", "bar"], packagePath: fooPath) XCTFail("Unexpected unedit success") } catch {} // Push the changes. try editsRepo.push(remote: "origin", branch: "bugfix") // We should be able to unedit now. _ = try SwiftPMProduct.SwiftPackage.execute(["unedit", "bar"], packagePath: fooPath) // Test editing with a path i.e. ToT development. let bazTot = prefix.appending(component: "tot") try SwiftPMProduct.SwiftPackage.execute(["edit", "baz", "--path", bazTot.asString], packagePath: fooPath) XCTAssertTrue(exists(bazTot)) XCTAssertTrue(isSymlink(bazEditsPath)) // Edit a file in baz ToT checkout. let bazTotPackageFile = bazTot.appending(component: "Package.swift") let stream = BufferedOutputByteStream() stream <<< (try localFileSystem.readFileContents(bazTotPackageFile)) <<< "\n// Edited." try localFileSystem.writeFileContents(bazTotPackageFile, bytes: stream.bytes) // Unediting baz will remove the symlink but not the checked out package. try SwiftPMProduct.SwiftPackage.execute(["unedit", "baz"], packagePath: fooPath) XCTAssertTrue(exists(bazTot)) XCTAssertFalse(isSymlink(bazEditsPath)) // Check that on re-editing with path, we don't make a new clone. try SwiftPMProduct.SwiftPackage.execute(["edit", "baz", "--path", bazTot.asString], packagePath: fooPath) XCTAssertTrue(isSymlink(bazEditsPath)) XCTAssertEqual(try localFileSystem.readFileContents(bazTotPackageFile), stream.bytes) } } func testPackageClean() throws { fixture(name: "DependencyResolution/External/Simple") { prefix in let packageRoot = prefix.appending(component: "Bar") // Build it. XCTAssertBuilds(packageRoot) let buildPath = packageRoot.appending(component: ".build") let binFile = buildPath.appending(components: Destination.host.target, "debug", "Bar") XCTAssertFileExists(binFile) XCTAssert(isDirectory(buildPath)) // Clean, and check for removal of the build directory but not Packages. _ = try execute(["clean"], packagePath: packageRoot) XCTAssert(!exists(binFile)) // Clean again to ensure we get no error. _ = try execute(["clean"], packagePath: packageRoot) } } func testPackageReset() throws { fixture(name: "DependencyResolution/External/Simple") { prefix in let packageRoot = prefix.appending(component: "Bar") // Build it. XCTAssertBuilds(packageRoot) let buildPath = packageRoot.appending(component: ".build") let binFile = buildPath.appending(components: Destination.host.target, "debug", "Bar") XCTAssertFileExists(binFile) XCTAssert(isDirectory(buildPath)) // Clean, and check for removal of the build directory but not Packages. _ = try execute(["clean"], packagePath: packageRoot) XCTAssert(!exists(binFile)) XCTAssertFalse(try localFileSystem.getDirectoryContents(buildPath.appending(component: "repositories")).isEmpty) // Fully clean. _ = try execute(["reset"], packagePath: packageRoot) XCTAssertFalse(isDirectory(buildPath)) // Test that we can successfully run reset again. _ = try execute(["reset"], packagePath: packageRoot) } } func testPinningBranchAndRevision() throws { fixture(name: "Miscellaneous/PackageEdit") { prefix in let fooPath = prefix.appending(component: "foo") @discardableResult func execute(_ args: String..., printError: Bool = true) throws -> String { return try SwiftPMProduct.SwiftPackage.execute([] + args, packagePath: fooPath) } try execute("update") let pinsFile = fooPath.appending(component: "Package.resolved") XCTAssert(exists(pinsFile)) // Update bar repo. let barPath = prefix.appending(component: "bar") let barRepo = GitRepository(path: barPath) try barRepo.checkout(newBranch: "YOLO") let yoloRevision = try barRepo.getCurrentRevision() // Try to pin bar at a branch. do { try execute("resolve", "bar", "--branch", "YOLO") let pinsStore = try PinsStore(pinsFile: pinsFile, fileSystem: localFileSystem) let state = CheckoutState(revision: yoloRevision, branch: "YOLO") XCTAssertEqual(pinsStore.pinsMap["bar"]!.state, state) } // Try to pin bar at a revision. do { try execute("resolve", "bar", "--revision", yoloRevision.identifier) let pinsStore = try PinsStore(pinsFile: pinsFile, fileSystem: localFileSystem) let state = CheckoutState(revision: yoloRevision) XCTAssertEqual(pinsStore.pinsMap["bar"]!.state, state) } // Try to pin bar at a bad revision. do { try execute("resolve", "bar", "--revision", "xxxxx") XCTFail() } catch {} } } func testPinning() throws { fixture(name: "Miscellaneous/PackageEdit") { prefix in let fooPath = prefix.appending(component: "foo") func build() throws -> String { let buildOutput = try SwiftPMProduct.SwiftBuild.execute([], packagePath: fooPath) return buildOutput } let exec = [fooPath.appending(components: ".build", Destination.host.target, "debug", "foo").asString] // Build and sanity check. _ = try build() XCTAssertEqual(try Process.checkNonZeroExit(arguments: exec).spm_chomp(), "\(5)") // Get path to bar checkout. let barPath = try SwiftPMProduct.packagePath(for: "bar", packageRoot: fooPath) // Checks the content of checked out bar.swift. func checkBar(_ value: Int, file: StaticString = #file, line: UInt = #line) throws { let contents = try localFileSystem.readFileContents(barPath.appending(components:"Sources", "bar.swift")).asString?.spm_chomp() XCTAssert(contents?.hasSuffix("\(value)") ?? false, file: file, line: line) } // We should see a pin file now. let pinsFile = fooPath.appending(component: "Package.resolved") XCTAssert(exists(pinsFile)) // Test pins file. do { let pinsStore = try PinsStore(pinsFile: pinsFile, fileSystem: localFileSystem) XCTAssertEqual(pinsStore.pins.map{$0}.count, 2) for pkg in ["bar", "baz"] { let pin = pinsStore.pinsMap[pkg]! XCTAssertEqual(pin.packageRef.identity, pkg) XCTAssert(pin.packageRef.repository.url.hasSuffix(pkg)) XCTAssertEqual(pin.state.version, "1.2.3") } } @discardableResult func execute(_ args: String...) throws -> String { return try SwiftPMProduct.SwiftPackage.execute([] + args, packagePath: fooPath) } // Try to pin bar. do { try execute("resolve", "bar") let pinsStore = try PinsStore(pinsFile: pinsFile, fileSystem: localFileSystem) XCTAssertEqual(pinsStore.pinsMap["bar"]!.state.version, "1.2.3") } // Update bar repo. do { let barPath = prefix.appending(component: "bar") let barRepo = GitRepository(path: barPath) try localFileSystem.writeFileContents(barPath.appending(components: "Sources", "bar.swift"), bytes: "public let theValue = 6\n") try barRepo.stageEverything() try barRepo.commit() try barRepo.tag(name: "1.2.4") } // Running package update with --repin should update the package. do { try execute("update") try checkBar(6) } // We should be able to revert to a older version. do { try execute("resolve", "bar", "--version", "1.2.3") let pinsStore = try PinsStore(pinsFile: pinsFile, fileSystem: localFileSystem) XCTAssertEqual(pinsStore.pinsMap["bar"]!.state.version, "1.2.3") try checkBar(5) } // Try pinning a dependency which is in edit mode. do { try execute("edit", "bar", "--branch", "bugfix") do { try execute("resolve", "bar") XCTFail("This should have been an error") } catch SwiftPMProductError.executionFailure(_, _, let stderr) { XCTAssertEqual(stderr, "error: dependency 'bar' already in edit mode\n") } try execute("unedit", "bar") } } } func testSymlinkedDependency() { mktmpdir { path in let fs = localFileSystem let root = path.appending(components: "root") let dep = path.appending(components: "dep") let depSym = path.appending(components: "depSym") // Create root package. try fs.writeFileContents(root.appending(components: "Sources", "root", "main.swift")) { $0 <<< "" } try fs.writeFileContents(root.appending(component: "Package.swift")) { $0 <<< """ // swift-tools-version:4.0 import PackageDescription let package = Package( name: "root", dependencies: [.package(url: "../depSym", from: "1.0.0")], targets: [.target(name: "root", dependencies: ["dep"])] ) """ } // Create dependency. try fs.writeFileContents(dep.appending(components: "Sources", "dep", "lib.swift")) { $0 <<< "" } try fs.writeFileContents(dep.appending(component: "Package.swift")) { $0 <<< """ // swift-tools-version:4.0 import PackageDescription let package = Package( name: "dep", products: [.library(name: "dep", targets: ["dep"])], targets: [.target(name: "dep")] ) """ } do { let depGit = GitRepository(path: dep) try depGit.create() try depGit.stageEverything() try depGit.commit() try depGit.tag(name: "1.0.0") } // Create symlink to the dependency. try createSymlink(depSym, pointingAt: dep) _ = try execute(["resolve"], packagePath: root) } } func testWatchmanXcodeprojgen() { mktmpdir { path in let fs = localFileSystem let diagnostics = DiagnosticsEngine() let scriptsDir = path.appending(component: "scripts") let packageRoot = path.appending(component: "root") let helper = WatchmanHelper( diagnostics: diagnostics, watchmanScriptsDir: scriptsDir, packageRoot: packageRoot) let script = try helper.createXcodegenScript( XcodeprojOptions(xcconfigOverrides: .init("/tmp/overrides.xcconfig"))) XCTAssertEqual(try fs.readFileContents(script), """ #!/usr/bin/env bash # Autogenerated by SwiftPM. Do not edit! set -eu swift package generate-xcodeproj --xcconfig-overrides /tmp/overrides.xcconfig """) } } func testMirrorConfig() { mktmpdir { prefix in let fs = localFileSystem let packageRoot = prefix.appending(component: "Foo") let configOverride = prefix.appending(component: "configoverride") let configFile = packageRoot.appending(components: ".swiftpm", "config") fs.createEmptyFiles(at: packageRoot, files: "/Sources/Foo/Foo.swift", "/Tests/FooTests/FooTests.swift", "/Package.swift", "anchor" ) // Test writing. try execute(["config", "set-mirror", "--package-url", "https://github.com/foo/bar", "--mirror-url", "https://mygithub.com/foo/bar"], packagePath: packageRoot) try execute(["config", "set-mirror", "--package-url", "[email protected]:apple/swift-package-manager.git", "--mirror-url", "[email protected]:foo/swift-package-manager.git"], packagePath: packageRoot) XCTAssertTrue(fs.isFile(configFile)) // Test env override. try execute(["config", "set-mirror", "--package-url", "https://github.com/foo/bar", "--mirror-url", "https://mygithub.com/foo/bar"], packagePath: packageRoot, env: ["SWIFTPM_MIRROR_CONFIG": configOverride.asString]) XCTAssertTrue(fs.isFile(configOverride)) XCTAssertTrue(try fs.readFileContents(configOverride).asString!.contains("mygithub")) // Test reading. XCTAssertEqual(try execute(["config", "get-mirror", "--package-url", "https://github.com/foo/bar"], packagePath: packageRoot), "https://mygithub.com/foo/bar") XCTAssertEqual(try execute(["config", "get-mirror", "--package-url", "[email protected]:apple/swift-package-manager.git"], packagePath: packageRoot), "[email protected]:foo/swift-package-manager.git") func check(stderr: String, _ block: () throws -> ()) { do { try block() XCTFail() } catch SwiftPMProductError.executionFailure(_, _, let stderrOutput) { XCTAssertEqual(stderrOutput, stderr) } catch { XCTFail("unexpected error: \(error)") } } check(stderr: "not found\n") { try execute(["config", "get-mirror", "--package-url", "foo"], packagePath: packageRoot) } // Test deletion. try execute(["config", "unset-mirror", "--package-url", "https://github.com/foo/bar"], packagePath: packageRoot) try execute(["config", "unset-mirror", "--mirror-url", "[email protected]:foo/swift-package-manager.git"], packagePath: packageRoot) check(stderr: "not found\n") { try execute(["config", "get-mirror", "--package-url", "https://github.com/foo/bar"], packagePath: packageRoot) } check(stderr: "not found\n") { try execute(["config", "get-mirror", "--package-url", "[email protected]:apple/swift-package-manager.git"], packagePath: packageRoot) } check(stderr: "error: mirror not found\n") { try execute(["config", "unset-mirror", "--package-url", "foo"], packagePath: packageRoot) } } } }
apache-2.0
6fcadadd75722f59c8915d8459529e51
44.658824
227
0.588287
5.070362
false
true
false
false
JTWang4778/JTLive
MuXueLive/UIViewExt.swift
1
1538
import UIKit import Foundation extension UIView { func x()->CGFloat { return self.frame.origin.x } func right()-> CGFloat { return self.frame.origin.x + self.frame.size.width } func y()->CGFloat { return self.frame.origin.y } func bottom()->CGFloat { return self.frame.origin.y + self.frame.size.height } func width()->CGFloat { return self.frame.size.width } func height()-> CGFloat { return self.frame.size.height } func setX(x: CGFloat) { var rect:CGRect = self.frame rect.origin.x = x self.frame = rect } func setRight(right: CGFloat) { var rect:CGRect = self.frame rect.origin.x = right - rect.size.width self.frame = rect } func setY(y: CGFloat) { var rect:CGRect = self.frame rect.origin.y = y self.frame = rect } func setBottom(bottom: CGFloat) { var rect:CGRect = self.frame rect.origin.y = bottom - rect.size.height self.frame = rect } func setWidth(width: CGFloat) { var rect:CGRect = self.frame rect.size.width = width self.frame = rect } func setHeight(height: CGFloat) { var rect:CGRect = self.frame rect.size.height = height self.frame = rect } class func showAlertView(title:String,message:String) { // 创建 } }
mit
a52f6f09f739306d066b63bf4a06f27b
18.175
59
0.533246
3.994792
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/Solutions/Medium/Medium_039_Combination_Sum.swift
1
1681
/* https://leetcode.com/problems/combination-sum/ #39 Combination Sum Level: medium Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will be positive integers. Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). The solution set must not contain duplicate combinations. For example, given candidate set 2,3,6,7 and target 7, A solution set is: [7] [2, 2, 3] Inspired by @dylan_yu at https://leetcode.com/discuss/10141/a-solution-avoid-using-set */ import Foundation struct Medium_039_Combination_Sum { private static func recurse(list: [Int], target: Int, candidates: [Int], index: Int, result: inout [[Int]]) { if target == 0 { result.append(list) return } for i in index ..< candidates.count { let newTarget: Int = target - candidates[i] if newTarget >= 0 { var copy: [Int] = Array<Int>(list) copy.append(candidates[i]) recurse(list: copy, target: newTarget, candidates: candidates, index: i, result: &result) } else { break } } } static func combinationSum(candidates cdts: [Int], target: Int) -> [[Int]] { var candidates = cdts var result: [[Int]] = [] candidates.sort {$0 < $1} recurse(list: [Int](), target: target, candidates: candidates, index: 0, result: &result) return result } }
mit
6b2a3ceff04f9d6cef35bc9237f99d3c
29.944444
134
0.618193
3.859122
false
false
false
false
andersklenke/ApiModel
Source/ApiForm.swift
1
9762
import RealmSwift import Alamofire public enum ApiFormModelStatus { case None case Successful(Int) case Unauthorized(Int) case Invalid(Int) case ServerError(Int) init(statusCode: Int) { if statusCode >= 200 && statusCode <= 299 { self = .Successful(statusCode) } else if statusCode == 401 { self = .Unauthorized(statusCode) } else if statusCode >= 400 && statusCode <= 499 { self = .Invalid(statusCode) } else if statusCode >= 500 && statusCode <= 599 { self = .ServerError(statusCode) } else { self = .None } } } public class ApiFormResponse<ModelType:Object where ModelType:ApiTransformable> { public var responseData: [String:AnyObject]? public var responseObject: [String:AnyObject]? public var responseArray: [AnyObject]? public var object: ModelType? public var array: [ModelType]? public var errors: [String:[String]]? public var rawResponse: ApiResponse? public var isSuccessful: Bool { for (key, errorsForKey) in errors ?? [:] { if !errorsForKey.isEmpty { return false } } return true } public var responseStatus: ApiFormModelStatus { if let status = rawResponse?.status { return ApiFormModelStatus(statusCode: status) } else { return .None } } } public class ApiForm<ModelType:Object where ModelType:ApiTransformable> { public typealias ResponseCallback = (ApiFormResponse<ModelType>) -> Void public var status: ApiFormModelStatus = .None public var errors: [String:[String]] = [:] public var model: ModelType public var errorMessages:[String] { var errorString: [String] = [] for (key, errorsForProperty) in errors { for message in errorsForProperty { if key == "base" { errorString.append(message) } else { errorString.append("\(key.capitalizedString) \(message)") } } } return errorString } public var hasErrors: Bool { return !errors.isEmpty } public init(model: ModelType) { self.model = model } public func updateFromForm(formParameters: NSDictionary) { model.modifyStoredObject { self.model.updateFromDictionaryWithMapping(formParameters as! [String:AnyObject], mapping: ModelType.fromJSONMapping()) } } public func updateFromResponse(response: ApiFormResponse<ModelType>) { if let statusCode = response.rawResponse?.status { self.status = ApiFormModelStatus(statusCode: statusCode) } if let responseObject = response.responseObject { model.modifyStoredObject { self.model.updateFromDictionaryWithMapping(responseObject, mapping: ModelType.fromJSONMapping()) } } if let errors = response.errors { self.errors = errors } } public class func fromApi(apiResponse: [String:AnyObject]) -> ModelType { let newModel = ModelType() newModel.updateFromDictionaryWithMapping(apiResponse, mapping: ModelType.fromJSONMapping()) return newModel } // api-model style methods public class func get(path: String, parameters: RequestParameters, callback: ResponseCallback?) { let call = ApiCall(method: .GET, path: path, parameters: parameters, namespace: ModelType.apiNamespace()) perform(call, callback: callback) } public class func get(path: String, callback: ResponseCallback?) { get(path, parameters: [:], callback: callback) } public class func post(path: String, parameters: RequestParameters, callback: ResponseCallback?) { let call = ApiCall(method: .POST, path: path, parameters: parameters, namespace: ModelType.apiNamespace()) perform(call, callback: callback) } public class func post(path: String, callback: ResponseCallback?) { post(path, parameters: [:], callback: callback) } public class func delete(path: String, parameters: RequestParameters, callback: ResponseCallback?) { let call = ApiCall(method: .DELETE, path: path, parameters: parameters, namespace: ModelType.apiNamespace()) perform(call, callback: callback) } public class func delete(path: String, callback: ResponseCallback?) { delete(path, parameters: [:], callback: callback) } public class func put(path: String, parameters: RequestParameters, callback: ResponseCallback?) { let call = ApiCall(method: .PUT, path: path, parameters: parameters, namespace: ModelType.apiNamespace()) perform(call, callback: callback) } public class func put(path: String, callback: ResponseCallback?) { put(path, parameters: [:], callback: callback) } // active record (rails) style methods public class func find(callback: (ModelType?) -> Void) { get(ModelType.apiRoutes().index) { response in callback(response.object) } } public class func findArray(callback: ([ModelType]) -> Void) { findArray(ModelType.apiRoutes().index, callback: callback) } public class func findArray(path: String, callback: ([ModelType]) -> Void) { get(path) { response in callback(response.array ?? []) } } public class func create(parameters: RequestParameters, callback: (ModelType?) -> Void) { post(ModelType.apiRoutes().create, parameters: parameters) { response in callback(response.object) } } public class func update(parameters: RequestParameters, callback: (ModelType?) -> Void) { put(ModelType.apiRoutes().update, parameters: parameters) { response in callback(response.object) } } public func save(callback: (ApiForm) -> Void) { let parameters: [String: AnyObject] = [ ModelType.apiNamespace(): model.JSONDictionary() ] let responseCallback: ResponseCallback = { response in self.updateFromResponse(response) callback(self) } if model.isApiSaved() { self.dynamicType.put(model.apiRouteWithReplacements(ModelType.apiRoutes().update), parameters: parameters, callback: responseCallback) } else { self.dynamicType.post(model.apiRouteWithReplacements(ModelType.apiRoutes().create), parameters: parameters, callback: responseCallback) } } public func destroy(callback: (ApiForm) -> Void) { destroy([:], callback: callback) } public func destroy(parameters: RequestParameters, callback: (ApiForm) -> Void) { self.dynamicType.delete(model.apiRouteWithReplacements(ModelType.apiRoutes().destroy), parameters: parameters) { response in self.updateFromResponse(response) callback(self) } } public class func perform(call: ApiCall, callback: ResponseCallback?) { api().request( call.method, path: call.path, parameters: call.parameters ) { data, error in var response = ApiFormResponse<ModelType>() response.rawResponse = data if let errors = self.errorFromResponse(nil, error: error) { response.errors = errors } if let data: AnyObject = data?.parsedResponse { response.responseData = data as? [String:AnyObject] if let responseObject = self.objectFromResponseForNamespace(data, namespace: call.namespace) { response.responseObject = responseObject response.object = self.fromApi(responseObject) if let errors = self.errorFromResponse(responseObject, error: error) { response.errors = errors } } else if let arrayData = self.arrayFromResponseForNamespace(data, namespace: call.namespace) { response.responseArray = arrayData response.array = [] for modelData in arrayData { if let modelDictionary = modelData as? [String:AnyObject] { response.array?.append(self.fromApi(modelDictionary)) } } } } callback?(response) } } private class func objectFromResponseForNamespace(data: AnyObject, namespace: String) -> [String:AnyObject]? { return (data[namespace] as? [String:AnyObject]) ?? (data[namespace.pluralize()] as? [String:AnyObject]) } private class func arrayFromResponseForNamespace(data: AnyObject, namespace: String) -> [AnyObject]? { return (data[namespace] as? [AnyObject]) ?? (data[namespace.pluralize()] as? [AnyObject]) } private class func errorFromResponse(response: [String:AnyObject]?, error: NSError?) -> [String:[String]]? { if let errors = response?["errors"] as? [String:[String]] { return errors } else if let errors = response?["errors"] as? [String] { return ["base": errors] } else if error != nil { return ["base": ["An unexpected server error occurred"]] } else { return nil } } }
mit
fda0a21f8cd608f609c6bb78999ba09d
35.977273
147
0.599775
5.17878
false
false
false
false
openHPI/xikolo-ios
Common/Data/Model/Channel.swift
1
1632
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import CoreData import Foundation import Stockpile public final class Channel: NSManagedObject { @NSManaged public var id: String @NSManaged public var title: String? @NSManaged public var channelDescription: String? @NSManaged public var colorString: String? @NSManaged public var position: Int16 @NSManaged public var imageURL: URL? @NSManaged public var stageStream: VideoStream? @NSManaged public var courses: Set<Course> @nonobjc public class func fetchRequest() -> NSFetchRequest<Channel> { return NSFetchRequest<Channel>(entityName: "Channel") } } extension Channel: JSONAPIPullable { public static var type: String { return "channels" } public func update(from object: ResourceData, with context: SynchronizationContext) throws { let attributes = try object.value(for: "attributes") as JSON self.title = try attributes.value(for: "title") self.channelDescription = try attributes.value(for: "description") self.colorString = try attributes.value(for: "color") self.position = try attributes.value(for: "position") self.imageURL = try attributes.failsafeURL(for: "mobile_image_url") self.stageStream = try attributes.value(for: "stage_stream") ?? self.stageStream if let relationships = try? object.value(for: "relationships") as JSON { try self.updateRelationship(forKeyPath: \Self.courses, forKey: "courses", fromObject: relationships, with: context) } } }
gpl-3.0
10eb9d76a48c2a876d966469fcc8be81
32.979167
127
0.698345
4.349333
false
false
false
false
jvlppm/pucpr-ios-arkanoid
pucpr-ios-classicmix/SoundEffects.swift
1
879
// // SoundEffects.swift // pucpr-ios-classicmix // // Created by Joao Vitor on 11/3/14. // Copyright (c) 2014 Joao Vitor. All rights reserved. // import Foundation import AVFoundation class SoundEffects { var player: AVAudioPlayer? = nil func bounce() { play("Bounce") } func hitBrick() { play("Hit_Hurt") } func destroyBrick() { play("Hit_Destroy") } func death() { play("Explosion") } func play(sound: String) { var fileUrl: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType: "wav")!)! var error: NSError? player = AVAudioPlayer(contentsOfURL: fileUrl, error: &error) player?.numberOfLoops = 0 player?.volume = Game.Settings.effectsVolume player?.prepareToPlay() player?.play() } }
mit
1767fa7007e58bafe9ca95839abe3ce6
21
114
0.593857
4.146226
false
false
false
false
stack-this/hunter-price
ios/Product.swift
1
837
// // Product.swift // HunterPrice // // Created by Gessy on 9/10/16. // Copyright © 2016 GetsemaniAvila. All rights reserved. // import Foundation class ProductData { class Product { let name : String let lowerPrice : String let higherPrice : String let quantity : String let unity : String let status : String let descripcion : String init(name: String, lowerPrice: String,higherPrice: String,quantity: String,unity: String,status: String,descripcion: String) { self.name = name self.lowerPrice = lowerPrice self.higherPrice = higherPrice self.quantity = quantity self.unity = unity self.status = status self.descripcion = descripcion } } }
apache-2.0
94d8e1250f7c3e2ede6f674bd572e0d9
21.594595
134
0.584928
4.42328
false
false
false
false
EaglesoftZJ/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AAAuthViewController.swift
1
4297
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation open class AAAuthViewController: AAViewController { open let nextBarButton = UIButton() var keyboardHeight: CGFloat = 0 override open func viewDidLoad() { super.viewDidLoad() nextBarButton.setTitle(AALocalized("NavigationNext"), for: UIControlState()) nextBarButton.setTitleColor(UIColor.white, for: UIControlState()) nextBarButton.setBackgroundImage(Imaging.roundedImage(UIColor(red: 94, green: 142, blue: 192), radius: 4), for: UIControlState()) nextBarButton.setBackgroundImage(Imaging.roundedImage(UIColor(red: 94, green: 142, blue: 192).alpha(0.7), radius: 4), for: .highlighted) nextBarButton.addTarget(self, action: #selector(AAAuthViewController.nextDidTap), for: .touchUpInside) view.addSubview(nextBarButton) } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() layoutNextBar() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Forcing initial layout before keyboard show to avoid weird animations layoutNextBar() NotificationCenter.default.addObserver(self, selector: #selector(AAAuthViewController.keyboardWillAppearInt(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) // NotificationCenter.default.addObserver(self, selector: #selector(AAAuthViewController.keyboardWillAppearInt(_:)), name:NSNotification.Name.UITextInputCurrentInputModeDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(AAAuthViewController.keyboardWillDisappearInt(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func layoutNextBar() { nextBarButton.frame = CGRect(x: view.width - 95, y: view.height - 44 - keyboardHeight + 6, width: 85, height: 32) } func keyboardWillAppearInt(_ notification: Notification) { let dict = (notification as NSNotification).userInfo! // let duration = (dict[UIKeyboardAnimationDurationUserInfoKey] as! Float) // let beginKeyboardRect = dict[UIKeyboardFrameBeginUserInfoKey] as! CGRect let endKeyBoardRect = dict[UIKeyboardFrameEndUserInfoKey] as! CGRect let heightCoveredByKeyboard = self.view.frame.size.height - endKeyBoardRect.origin.y // let rect = (dict[UIKeyboardFrameBeginUserInfoKey]! as AnyObject).cgRectValue // // let orientation = UIApplication.shared.statusBarOrientation // let frameInWindow = self.view.superview!.convert(view.bounds, to: nil) // let windowBounds = view.window!.bounds // // let keyboardTop: CGFloat = windowBounds.size.height - rect!.height // let heightCoveredByKeyboard: CGFloat // if AADevice.isiPad { // if orientation == .landscapeLeft || orientation == .landscapeRight { // heightCoveredByKeyboard = frameInWindow.maxY - keyboardTop - 52 /*???*/ // } else if orientation == .portrait || orientation == .portraitUpsideDown { // heightCoveredByKeyboard = frameInWindow.maxY - keyboardTop // } else { // heightCoveredByKeyboard = 0 // } // } else { // heightCoveredByKeyboard = (rect?.height)! // } keyboardHeight = max(0, heightCoveredByKeyboard) layoutNextBar() keyboardWillAppear(keyboardHeight) } func keyboardWillDisappearInt(_ notification: Notification) { keyboardHeight = 0 layoutNextBar() keyboardWillDisappear() } open func keyboardWillAppear(_ height: CGFloat) { } open func keyboardWillDisappear() { } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) keyboardHeight = 0 layoutNextBar() } /// Call this method when authentication successful open func onAuthenticated() { ActorSDK.sharedActor().didLoggedIn() } open func nextDidTap() { } }
agpl-3.0
ad56b629f8eb1b9078831165d9aa014a
38.787037
199
0.663253
5.425505
false
false
false
false
robinckanatzar/mcw
my-core-wellness/my-core-wellness/RedFlagsVC.swift
1
854
// // RedFlagsVC.swift // my-core-wellness // // Created by Robin Kanatzar on 3/18/17. // Copyright © 2017 Robin Kanatzar. All rights reserved. // import Foundation import UIKit import AVFoundation class RedFlagsVC : UIViewController { @IBOutlet weak var back: UIBarButtonItem! @IBOutlet weak var navigationBar: UINavigationBar! override func viewDidLoad() { // set background self.view.backgroundColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0) // set up navigation bar navigationItem.leftBarButtonItem = back back.action = #selector(backAction) self.navigationItem.title = "Red Flags" navigationBar.topItem?.title = "Red Flags" } func backAction(){ dismiss(animated: true, completion: nil) } }
apache-2.0
3434140ead2d94020289ff279c81c513
24.848485
106
0.645955
4.140777
false
false
false
false
neils4fun/NRSPieChart
NRSPieChart/Classes/NRSPieChartView.swift
1
23024
// // NRSPieChart.swift // Pods // // Created by Neil Schreiber on 2/6/17. // // import Foundation import QuartzCore import UIKit @objc public protocol NRSPieChartViewDataSourceProtocol : NSObjectProtocol { // Return the number of major slices in the chart func numberOfMajorSlicesInPieChartView(_ pieChartView: NRSPieChartView) -> UInt // Return the number of minor slices for the given major slice func numberOfMinorSlicesInPieChartView(_ pieChartView: NRSPieChartView, forMajorSlice majorSlice: UInt) -> UInt // Return the color for the major/minor slice func pieChartColorForSlice(_ pieChartView: NRSPieChartView, sliceIndex: NRSPieChartViewSliceIndex) -> CGColor // Return end points of a major/minor slice index These end points are in terms of circumfrencial percentage of a full circle func pieChartEndPointsForSlice(_ pieChartView: NRSPieChartView, sliceIndex: NRSPieChartViewSliceIndex) -> NRSPieChartViewEndPoints // Return the major slice that will remain after slices are removed on a refresh. This is to support allowing the slices to grow out // from their current position when one is transitioning between slices that represent some kind of a hierarchy @objc optional func pieChartMajorSliceToKeepHint(_ pieChartView: NRSPieChartView) -> UInt // Default is 0 if not implemented // Return whether the major/minor slice should highlight. Highlighted slices are displayed slightly wider than their unhighlighted presentation @objc optional func pieChartShouldHighlightSlice(_ pieChartView: NRSPieChartView, sliceIndex: NRSPieChartViewSliceIndex) -> Bool // Default is false if not implemented @objc optional func pieChartDidFinishRendering(_ pieChartView: NRSPieChartView) } @objc public protocol NRSPieChartViewDelegateProtocol : NSObjectProtocol { @objc optional func pieChartDidSingleTapSlice(_ pieChartView: NRSPieChartView, sliceIndex: NRSPieChartViewSliceIndex) @objc optional func pieChartDidDoubleTapSlice(_ pieChartView: NRSPieChartView, sliceIndex: NRSPieChartViewSliceIndex) } @objcMembers @IBDesignable // IB_DESIGNABLE public class NRSPieChartView: UIView { #if !TARGET_INTERFACE_BUILDER weak public var dataSource: NRSPieChartViewDataSourceProtocol? weak public var delegate: NRSPieChartViewDelegateProtocol? #else // If IB the datasource isn't working if declared as weak because since // the datasource gets assigned within this classes init (see addBehavior() // below) the property is immediately released since afer the assignment // ARC sees no need to retain a weak property. So if IB I declare the // property as strong. public var dataSource: NRSPieChartViewDataSourceProtocol? public var delegate: NRSPieChartViewDelegateProtocol? #endif public var shouldAnimate: Bool = false @IBInspectable var bInset: CGFloat = 5 { didSet { updateLayerProperties() } } @IBInspectable var sInset: CGFloat = 10 { didSet { updateLayerProperties() } } @IBInspectable var bLineWidth: CGFloat = 30.0 { didSet { updateLayerProperties() } } @IBInspectable var sLineWidth: CGFloat = 20.0 { didSet { updateLayerProperties() } } @IBInspectable var bColor: UIColor = UIColor(white: 0.0, alpha: 1.0) { didSet { updateLayerProperties() } } @IBInspectable var bSRadius: CGFloat = 0.0 { didSet { updateLayerProperties() } } @IBInspectable var bSOpacity: Float = 5.0 { didSet { updateLayerProperties() } } @IBInspectable var sSRadius: CGFloat = 0.0 { didSet { updateLayerProperties() } } @IBInspectable var sSOpacity: Float = 5.0 { didSet { updateLayerProperties() } } @IBInspectable var duration: Float = 0.3 { didSet { updateLayerProperties() } } fileprivate var backgroundRingLayer: CAShapeLayer! fileprivate var pieSegments = [CAShapeLayer]() fileprivate var dirty = true override init (frame : CGRect) { super.init(frame : frame) commonInit() } required public init!(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit (){ #if !TARGET_INTERFACE_BUILDER // this code will run in the app itself #else // this code will execute only in IB dataSource = PieChartViewDataSource() #endif let pieChartSingleTapGestureRecoginize = UITapGestureRecognizer() pieChartSingleTapGestureRecoginize.addTarget(self, action: #selector(NRSPieChartView.pieChartTapped(_:))) pieChartSingleTapGestureRecoginize.numberOfTapsRequired = 1 self.addGestureRecognizer(pieChartSingleTapGestureRecoginize) let pieChartDoubleTapGestureRecoginize = UITapGestureRecognizer() pieChartDoubleTapGestureRecoginize.addTarget(self, action: #selector(NRSPieChartView.pieChartTapped(_:))) pieChartDoubleTapGestureRecoginize.numberOfTapsRequired = 2 self.addGestureRecognizer(pieChartDoubleTapGestureRecoginize) pieChartSingleTapGestureRecoginize.require(toFail: pieChartDoubleTapGestureRecoginize) // Create the background layer backgroundRingLayer = CAShapeLayer() backgroundRingLayer.rasterizationScale = 2.0 * UIScreen.main.scale; backgroundRingLayer.shouldRasterize = true; layer.addSublayer(backgroundRingLayer) } override public func layoutSubviews() { super.layoutSubviews() let totalInset: CGFloat = bInset + bLineWidth/2.0 let rect = bounds.insetBy(dx: totalInset, dy: totalInset) let center = CGPoint(x: bounds.width/2.0, y: bounds.height/2.0) let twoPi = 2.0 * Double.pi let startAngle = -Double.pi/2 //Double(fractionOfCircle) * Double(twoPi) - Double(M_PI_2) let endAngle = twoPi - Double.pi/2 let clockwise: Bool = true let path = UIBezierPath(arcCenter: center, radius: rect.height/2.0, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: clockwise) backgroundRingLayer.path = path.cgPath backgroundRingLayer.lineWidth = bLineWidth backgroundRingLayer.fillColor = nil; backgroundRingLayer.strokeColor = bColor.cgColor backgroundRingLayer.shadowColor = UIColor.black.cgColor backgroundRingLayer.shadowRadius = bSRadius backgroundRingLayer.shadowOpacity = bSOpacity/10.0 backgroundRingLayer.shadowOffset = CGSize(width: -3, height: 3) backgroundRingLayer.frame = layer.bounds if dirty { for layer in pieSegments { layer.removeFromSuperlayer() } pieSegments.removeAll() self.refreshSlices() shouldAnimate = false dirty = false } } public func refreshSlices() { let numLinearSlices = self.numLinearSlices() // Disable implicit CALayer animiations CATransaction.setDisableActions(true) // Determine if layers are going to be removed, added, or remain the same if (numLinearSlices == UInt(pieSegments.count)) { // Same number of slices, just update all the endpoints for (index, ringLayer) in pieSegments.enumerated() { let sliceIndex = self.sliceIndexForLinearIndex(UInt(index)) if let strokeColor = dataSource?.pieChartColorForSlice(self, sliceIndex: sliceIndex) { // Setup a custom animation for the color change, for which we can set a programmable "duration" value animateLayer(ringLayer, strokeColor: strokeColor, shouldAnimate: shouldAnimate, duration: duration) } if let endPoints = dataSource?.pieChartEndPointsForSlice(self, sliceIndex:sliceIndex) { animateLayer(ringLayer, strokeStart: endPoints.start/100, shouldAnimate: shouldAnimate, duration: duration) animateLayer(ringLayer, strokeEnd: endPoints.end/100, shouldAnimate: shouldAnimate, duration: duration) } let shouldHighlight = dataSource?.pieChartShouldHighlightSlice?(self, sliceIndex: sliceIndex) ?? false if (shouldHighlight) { ringLayer.lineWidth = sLineWidth + 4 } else { ringLayer.lineWidth = sLineWidth } } } else if (numLinearSlices < UInt(pieSegments.count)) { // There are fewer slices now. Update the endpoints of the existing // ones and then remove any extras let refreshSliceOffset = dataSource?.pieChartMajorSliceToKeepHint?(self) ?? 0 for index in 0..<UInt(pieSegments.count) { let ringLayer = pieSegments[Int(index)] ringLayer.removeAllAnimations() if (index < refreshSliceOffset) { // This segment is going away, animate it out animateLayer(ringLayer, strokeStart: 0.0, shouldAnimate: shouldAnimate, duration: duration) animateLayer(ringLayer, strokeEnd: 0.0, shouldAnimate: shouldAnimate, duration: duration) } else if (index >= refreshSliceOffset + numLinearSlices) { // This segment is going away, animate it out animateLayer(ringLayer, strokeStart: 1.0, shouldAnimate: shouldAnimate, duration: duration) animateLayer(ringLayer, strokeEnd: 1.0, shouldAnimate: shouldAnimate, duration: duration) } else { let sliceIndex = self.sliceIndexForLinearIndex(UInt(index - refreshSliceOffset)) if let strokeColor = dataSource?.pieChartColorForSlice(self, sliceIndex: sliceIndex) { animateLayer(ringLayer, strokeColor: strokeColor, shouldAnimate: shouldAnimate, duration: duration) } if let endPoints = dataSource?.pieChartEndPointsForSlice(self, sliceIndex:sliceIndex) { animateLayer(ringLayer, strokeStart: endPoints.start/100, shouldAnimate: shouldAnimate, duration: duration) animateLayer(ringLayer, strokeEnd: endPoints.end/100, shouldAnimate: shouldAnimate, duration: duration) } let shouldHighlight = dataSource?.pieChartShouldHighlightSlice?(self, sliceIndex: sliceIndex) ?? false if (shouldHighlight) { ringLayer.lineWidth = sLineWidth + 4 } else { ringLayer.lineWidth = sLineWidth } } } // Remove the extra layers, but defer it until the animations are complete var beforeSectionSlicesToRemove = [CAShapeLayer]() var afterSectionSlicesToRemove = [CAShapeLayer]() for index in 0..<refreshSliceOffset { beforeSectionSlicesToRemove.append(pieSegments[Int(index)]) } for index in Int(refreshSliceOffset + numLinearSlices)..<pieSegments.count { afterSectionSlicesToRemove.append(pieSegments[Int(index)]) } let delayTime = DispatchTime.now() + Double(Int64(Double(duration) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime) { beforeSectionSlicesToRemove.forEach { layer in layer.removeFromSuperlayer() } afterSectionSlicesToRemove.forEach { layer in layer.removeFromSuperlayer() } } pieSegments[Int(refreshSliceOffset + numLinearSlices)..<pieSegments.count] = [] pieSegments[0..<Int(refreshSliceOffset)] = [] } else { // There are more slices now. Add new ones. // Set the current colors and sizes of all the segments for (index, ringLayer) in pieSegments.enumerated() { let sliceIndex = self.sliceIndexForLinearIndex(UInt(index)) if let strokeColor = dataSource?.pieChartColorForSlice(self, sliceIndex: sliceIndex) { animateLayer(ringLayer, strokeColor: strokeColor, shouldAnimate: shouldAnimate, duration: duration) } if let endPoints = dataSource?.pieChartEndPointsForSlice(self, sliceIndex:sliceIndex) { animateLayer(ringLayer, strokeStart: endPoints.start/100, shouldAnimate: shouldAnimate, duration: duration) animateLayer(ringLayer, strokeEnd: endPoints.end/100, shouldAnimate: shouldAnimate, duration: duration) } let shouldHighlight = dataSource?.pieChartShouldHighlightSlice?(self, sliceIndex: sliceIndex) ?? false if (shouldHighlight) { ringLayer.lineWidth = sLineWidth + 4 } else { ringLayer.lineWidth = sLineWidth } } for index in UInt(pieSegments.count)..<numLinearSlices { let ringLayer = CAShapeLayer() let totalInset: CGFloat = sInset + sLineWidth/2.0 let innerRect = bounds.insetBy(dx: totalInset, dy: totalInset) let center = CGPoint(x: bounds.width/2.0, y: bounds.height/2.0) let twoPi = 2.0 * Double.pi let startAngle = -Double.pi/2 //Double(fractionOfCircle) * Double(twoPi) - Double(M_PI_2) let endAngle = twoPi - Double.pi/2 let clockwise: Bool = true let innerPath = UIBezierPath(arcCenter: center, radius: innerRect.height/2.0, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: clockwise) ringLayer.rasterizationScale = 2.0 * UIScreen.main.scale; ringLayer.shouldRasterize = true; ringLayer.path = innerPath.cgPath ringLayer.fillColor = nil let sliceIndex = self.sliceIndexForLinearIndex(UInt(index)) let shouldHighlight = dataSource?.pieChartShouldHighlightSlice?(self, sliceIndex: sliceIndex) ?? false if (shouldHighlight) { ringLayer.lineWidth = sLineWidth + 4 } else { ringLayer.lineWidth = sLineWidth } ringLayer.shadowColor = UIColor.black.cgColor ringLayer.shadowRadius = sSRadius ringLayer.shadowOpacity = sSOpacity/10.0 ringLayer.shadowOffset = CGSize.zero ringLayer.strokeColor = dataSource!.pieChartColorForSlice(self, sliceIndex:sliceIndex) ringLayer.strokeStart = 1.0 ringLayer.strokeEnd = 1.0 layer.addSublayer(ringLayer) ringLayer.frame = layer.bounds pieSegments.append(ringLayer) if let endPoints = dataSource?.pieChartEndPointsForSlice(self, sliceIndex:sliceIndex) { animateLayer(ringLayer, strokeStart: endPoints.start/100, shouldAnimate: shouldAnimate, duration: duration) animateLayer(ringLayer, strokeEnd: endPoints.end/100, shouldAnimate: shouldAnimate, duration: duration) } } } // Re-enable implicit CALayer animiations CATransaction.setDisableActions(false) dataSource?.pieChartDidFinishRendering?(self) } public func centerPointFor(_ majorSlice: UInt) -> CGPoint { guard majorSlice < dataSource?.numberOfMajorSlicesInPieChartView(self) ?? 0 else { return CGPoint(x: 0, y: 0) } var numLinearSlices: UInt = 0 var segmentAtStart: CAShapeLayer var segmentAtEnd: CAShapeLayer // Find the pieSegment for the first minor slice of the specified major for majorIndex in 0..<majorSlice { let numMinorSlices = dataSource?.numberOfMinorSlicesInPieChartView(self, forMajorSlice: majorIndex) ?? 0 for _ in 0..<numMinorSlices { numLinearSlices += 1 } } segmentAtStart = pieSegments[Int(numLinearSlices)]; // Find the pieSegment for the last minor slice of the specfied major let numMinorSlices = dataSource?.numberOfMinorSlicesInPieChartView(self, forMajorSlice: majorSlice) ?? 0 for _ in 0..<numMinorSlices { numLinearSlices += 1 } // Note, -1 index to get the last minor slice in the major segmentAtEnd = pieSegments[Int(numLinearSlices - 1)]; // Midpoint of major slice in terms of stroke distance let sliceStrokeMid = segmentAtStart.strokeStart + (segmentAtEnd.strokeEnd - segmentAtStart.strokeStart)/2.0 // Convert stroke terms to angle terms. NOTE: rotate left by 90 degrees to account for 0 degrees defined as vertical/up let twoPi = 2.0 * Double.pi let midAngle = Double(sliceStrokeMid) * twoPi - Double.pi/2; // Compute the x,y coordinate (in view coordinates) from the radial coordinate let x = bounds.origin.x + bounds.size.width/2.0 + (frame.height/2 - sInset - sLineWidth/2.0) * CGFloat(cos(midAngle)) let y = bounds.size.height - (bounds.origin.y + bounds.size.height/2 - ((frame.height/2.0 - sInset - sLineWidth/2.0) * CGFloat(sin(midAngle)))) return CGPoint(x: x, y: y) } func updateLayerProperties() { dirty = true setNeedsLayout() } } // MARK: - Animate Layer Properties extension NRSPieChartView { func animateLayer(_ layer: CAShapeLayer, strokeColor: CGColor, shouldAnimate: Bool, duration: Float) { // Setup a custom animation for layers strokeColor property if (shouldAnimate) { let strokeColorAnimation = CABasicAnimation(keyPath: "strokeColor") strokeColorAnimation.fromValue = layer.strokeColor strokeColorAnimation.toValue = strokeColor strokeColorAnimation.duration = CFTimeInterval(duration) layer.add(strokeColorAnimation, forKey: "StrokeColorAnimation") } layer.strokeColor = strokeColor } func animateLayer(_ layer: CAShapeLayer, strokeStart: CGFloat, shouldAnimate: Bool, duration: Float) { // Setup a custom animination for the layer's strokeStart property if (shouldAnimate) { let strokeStartAnimation = CABasicAnimation(keyPath: "strokeStart") strokeStartAnimation.fromValue = layer.strokeStart strokeStartAnimation.toValue = strokeStart strokeStartAnimation.duration = CFTimeInterval(duration) layer.add(strokeStartAnimation, forKey: "StrokeStartAnimation") } layer.strokeStart = strokeStart } func animateLayer(_ layer: CAShapeLayer, strokeEnd: CGFloat, shouldAnimate: Bool, duration: Float) { // Setup a custom animination for the layer's strokeEnd property if (shouldAnimate) { let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd") strokeEndAnimation.fromValue = layer.strokeEnd strokeEndAnimation.toValue = strokeEnd strokeEndAnimation.duration = CFTimeInterval(duration) layer.add(strokeEndAnimation, forKey: "StrokeEndAnimation") } layer.strokeEnd = strokeEnd } } // MARK: - Slice Index to Linear Index conversions extension NRSPieChartView { func numLinearSlices() -> UInt { var numLinearSlices: UInt = 0 var numMajorSlices: UInt numMajorSlices = dataSource?.numberOfMajorSlicesInPieChartView(self) ?? 0 for majorIndex in 0..<numMajorSlices { let numMinorSlices = dataSource?.numberOfMinorSlicesInPieChartView(self, forMajorSlice: majorIndex) ?? 0 for _ in 0..<numMinorSlices { numLinearSlices += 1 } } return numLinearSlices } func sliceIndexForLinearIndex(_ linearIndex: UInt) -> NRSPieChartViewSliceIndex { var linearIndex = linearIndex var majorIndex: UInt = 0 let numMajorSlices = dataSource?.numberOfMajorSlicesInPieChartView(self) ?? 0 for index in 0..<numMajorSlices { majorIndex = index let numMinorSlices = dataSource?.numberOfMinorSlicesInPieChartView(self, forMajorSlice: index) ?? 0 if linearIndex < numMinorSlices { break } linearIndex -= numMinorSlices } return NRSPieChartViewSliceIndex(major: majorIndex, minor: linearIndex) } } // MARK: - Gesture Recognizer Handling extension NRSPieChartView { @objc func pieChartTapped(_ sender:UITapGestureRecognizer) { let touchPoint = sender.location(in: self) let center = CGPoint(x: bounds.width/2.0, y: bounds.height/2.0) // Since our frame of reference is rotated -90 compute deltaX as the change in Y, // and deltaY as the change X (confusing, but should work). let deltaX = (center.y - touchPoint.y) let deltaY = (center.x - touchPoint.x) let thetaRadians = atan2(Double(deltaY),Double(deltaX)) let thetaDegrees = thetaRadians * 180/Double.pi let theta360Degrees = 360.0 - (thetaDegrees > 0.0 ? thetaDegrees : (360.0 + thetaDegrees)) let theta360Percent = theta360Degrees / 360.0 for (index,layer) in pieSegments.enumerated() { if (layer.hitTest(touchPoint) != nil) { if (CGFloat(theta360Percent) > layer.strokeStart && CGFloat(theta360Percent) <= layer.strokeEnd) { let sliceIndex = self.sliceIndexForLinearIndex(UInt(index)) if (sender.numberOfTapsRequired == 1) { delegate?.pieChartDidSingleTapSlice?(self, sliceIndex:sliceIndex) } else { delegate?.pieChartDidDoubleTapSlice?(self, sliceIndex:sliceIndex) } return; } } } } }
mit
a1b0ef572be3b8a8dbb62191cee54248
45.232932
177
0.626346
5.735924
false
false
false
false
superk589/DereGuide
DereGuide/Toolbox/MusicInfo/Detail/View/SongDetailDescriptionCell.swift
2
1019
// // SongDetailDescriptionCell.swift // DereGuide // // Created by zzk on 28/09/2017. // Copyright © 2017 zzk. All rights reserved. // import UIKit class SongDetailDescriptionCell: ReadableWidthTableViewCell { let label = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) readableContentView.addSubview(label) label.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.left.right.equalToSuperview() make.bottom.equalTo(-10) make.top.equalTo(10) } label.numberOfLines = 0 label.font = UIFont.systemFont(ofSize: 14) label.textColor = .darkGray label.textAlignment = .center } func setup(text: String) { label.text = text } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
21539b8ed475d3f3c49f66742e026d3d
25.789474
79
0.631631
4.524444
false
false
false
false
ahernandezlopez/Preacher
PreacherTests/CompositePredicate+NSPredicatable.swift
1
4404
// // CompositePredicate+NSPredicatable.swift // Preacher // // Created by Albert Hernández López on 2/6/15. // Copyright (c) 2015 Albert Hernández López. All rights reserved. // import Foundation import Quick import Nimble import Preacher class CompositePredicateNSPredicatable: QuickSpec { override func spec() { let alice = Person(firstName: "Alice", lastName: "Smith", age: 24) let bob = Person(firstName: "Bob", lastName: "Jones", age: 27) let charlie = Person(firstName: "Charlie", lastName: "Smith", age: 33) let quentin = Person(firstName: "Quentin", lastName: "Alberts", age: 31) let people: NSArray = [alice, bob, charlie, quentin] describe("not") { it("using not method") { let sut = "age".equals(24).not() let predicate = sut.nsPredicate() expect(predicate.predicateFormat).to(equal("NOT age == 24")) let filteredArray = people.filteredArrayUsingPredicate(predicate) let expectedResult: NSArray = [bob, charlie, quentin] expect(filteredArray).to(equal(expectedResult)) } it("using ! operand") { let sut = !"age".equals(24) let predicate = sut.nsPredicate() expect(predicate.predicateFormat).to(equal("NOT age == 24")) let filteredArray = people.filteredArrayUsingPredicate(predicate) let expectedResult: NSArray = [bob, charlie, quentin] expect(filteredArray).to(equal(expectedResult)) } } describe("and") { it("using and method") { let sut = "lastName".equals("Smith").and("age".equals(24)) let predicate = sut.nsPredicate() expect(predicate.predicateFormat).to(equal("lastName == \"Smith\" AND age == 24")) let filteredArray = people.filteredArrayUsingPredicate(predicate) let expectedResult: NSArray = [alice] expect(filteredArray).to(equal(expectedResult)) } it("using && operand") { let sut = "lastName".equals("Smith") && "age".equals(24) let predicate = sut.nsPredicate() expect(predicate.predicateFormat).to(equal("lastName == \"Smith\" AND age == 24")) let filteredArray = people.filteredArrayUsingPredicate(predicate) let expectedResult: NSArray = [alice] expect(filteredArray).to(equal(expectedResult)) } } describe("or") { it("using or method") { let sut = "lastName".equals("Smith").or("age".equals(24)) let predicate = sut.nsPredicate() expect(predicate.predicateFormat).to(equal("lastName == \"Smith\" OR age == 24")) let filteredArray = people.filteredArrayUsingPredicate(predicate) let expectedResult: NSArray = [alice, charlie] expect(filteredArray).to(equal(expectedResult)) } it("using || operand") { let sut = "lastName".equals("Smith") || "age".equals(24) let predicate = sut.nsPredicate() expect(predicate.predicateFormat).to(equal("lastName == \"Smith\" OR age == 24")) let filteredArray = people.filteredArrayUsingPredicate(predicate) let expectedResult: NSArray = [alice, charlie] expect(filteredArray).to(equal(expectedResult)) } } describe("mixed up") { it("using not, or & and") { let sut = (!"lastName".equals("Smith") || "firstName".equals("Charlie")) && "age".gt(30) let predicate = sut.nsPredicate() expect(predicate.predicateFormat).to(equal("((NOT lastName == \"Smith\") OR firstName == \"Charlie\") AND age > 30")) let filteredArray = people.filteredArrayUsingPredicate(predicate) let expectedResult: NSArray = [charlie, quentin] expect(filteredArray).to(equal(expectedResult)) } } } }
mit
c77808c8e7c67aa750490b3ba48957d3
41.728155
133
0.541364
5.219454
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/DerivableRequestTests.swift
1
15832
import XCTest import GRDB private struct Author: FetchableRecord, PersistableRecord, Codable { var id: Int64 var firstName: String? var lastName: String? var country: String var fullName: String { [firstName, lastName] .compactMap { $0 } .joined(separator: " ") } static let databaseTableName = "author" static let books = hasMany(Book.self) var books: QueryInterfaceRequest<Book> { request(for: Author.books) } } private struct Book: FetchableRecord, PersistableRecord, Codable { var id: Int64 var authorId: Int64 var title: String static let databaseTableName = "book" static let author = belongsTo(Author.self) static let bookFts4 = hasOne(BookFts4.self, using: ForeignKey([.rowID])) #if SQLITE_ENABLE_FTS5 static let bookFts5 = hasOne(BookFts5.self, using: ForeignKey([.rowID])) #endif var author: QueryInterfaceRequest<Author> { request(for: Book.author) } } private struct BookFts4: TableRecord { } #if SQLITE_ENABLE_FTS5 private struct BookFts5: TableRecord { } #endif private var libraryMigrator: DatabaseMigrator = { var migrator = DatabaseMigrator() migrator.registerMigration("library") { db in try db.create(table: "author") { t in t.autoIncrementedPrimaryKey("id") t.column("firstName", .text) t.column("lastName", .text) t.column("country", .text).notNull() } try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") t.column("authorId", .integer).notNull().references("author") t.column("title", .text).notNull() } try db.create(virtualTable: "bookFts4", using: FTS4()) { t in t.synchronize(withTable: "book") t.column("title") } #if SQLITE_ENABLE_FTS5 try db.create(virtualTable: "bookFts5", using: FTS5()) { t in t.synchronize(withTable: "book") t.column("title") } #endif } migrator.registerMigration("fixture") { db in try Author(id: 1, firstName: "Herman", lastName: "Melville", country: "US").insert(db) try Author(id: 2, firstName: "Marcel", lastName: "Proust", country: "FR").insert(db) try Book(id: 1, authorId: 1, title: "Moby-Dick").insert(db) try Book(id: 2, authorId: 2, title: "Du côté de chez Swann").insert(db) } return migrator }() // Define DerivableRequest extensions extension DerivableRequest<Author> { // SelectionRequest func selectCountry() -> Self { select(Column("country")) } // FilteredRequest func filter(country: String) -> Self { filter(Column("country") == country) } // OrderedRequest func orderByFullName() -> Self { order( Column("lastName").collating(.localizedCaseInsensitiveCompare), Column("firstName").collating(.localizedCaseInsensitiveCompare)) } } extension DerivableRequest<Book> { // OrderedRequest func orderByTitle() -> Self { order(Column("title").collating(.localizedCaseInsensitiveCompare)) } // JoinableRequest func filter(authorCountry: String) -> Self { joining(required: Book.author.filter(country: authorCountry)) } // TableRequest & FilteredRequest func filter(id: Int) -> Self { filter(key: id) } // TableRequest & FilteredRequest func matchingFts4(_ pattern: FTS3Pattern?) -> Self { joining(required: Book.bookFts4.matching(pattern)) } #if SQLITE_ENABLE_FTS5 // TableRequest & FilteredRequest func matchingFts5(_ pattern: FTS3Pattern?) -> Self { joining(required: Book.bookFts5.matching(pattern)) } #endif // TableRequest & OrderedRequest func orderById() -> Self { orderByPrimaryKey() } } class DerivableRequestTests: GRDBTestCase { func testFilteredRequest() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in // ... for two requests (1) let frenchAuthorNames = try Author.all() .filter(country: "FR") .fetchAll(db) .map(\.fullName) XCTAssertEqual(frenchAuthorNames, ["Marcel Proust"]) // ... for two requests (2) let frenchBookTitles = try Book .joining(required: Book.author.filter(country: "FR")) .order(Column("title")) .fetchAll(db) .map(\.title) XCTAssertEqual(frenchBookTitles, ["Du côté de chez Swann"]) } } func testOrderedRequest() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in // ... for two requests (1) sqlQueries.removeAll() let authorNames = try Author.all() .orderByFullName() .fetchAll(db) .map(\.fullName) XCTAssertEqual(authorNames, ["Herman Melville", "Marcel Proust"]) XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "author" \ ORDER BY "lastName" COLLATE swiftLocalizedCaseInsensitiveCompare, \ "firstName" COLLATE swiftLocalizedCaseInsensitiveCompare """) sqlQueries.removeAll() let reversedAuthorNames = try Author.all() .orderByFullName() .reversed() .fetchAll(db) .map(\.fullName) XCTAssertEqual(reversedAuthorNames, ["Marcel Proust", "Herman Melville"]) XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "author" \ ORDER BY "lastName" COLLATE swiftLocalizedCaseInsensitiveCompare DESC, \ "firstName" COLLATE swiftLocalizedCaseInsensitiveCompare DESC """) sqlQueries.removeAll() _ /* unorderedAuthors */ = try Author.all() .orderByFullName() .unordered() .fetchAll(db) XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "author" """) // ... for two requests (2) sqlQueries.removeAll() let bookTitles = try Book .joining(required: Book.author.orderByFullName()) .orderByTitle() .fetchAll(db) .map(\.title) XCTAssertEqual(bookTitles, ["Du côté de chez Swann", "Moby-Dick"]) XCTAssertEqual(lastSQLQuery, """ SELECT "book".* FROM "book" \ JOIN "author" ON "author"."id" = "book"."authorId" \ ORDER BY \ "book"."title" COLLATE swiftLocalizedCaseInsensitiveCompare, \ "author"."lastName" COLLATE swiftLocalizedCaseInsensitiveCompare, \ "author"."firstName" COLLATE swiftLocalizedCaseInsensitiveCompare """) sqlQueries.removeAll() let reversedBookTitles = try Book .joining(required: Book.author.orderByFullName()) .orderByTitle() .reversed() .fetchAll(db) .map(\.title) XCTAssertEqual(reversedBookTitles, ["Moby-Dick", "Du côté de chez Swann"]) XCTAssertEqual(lastSQLQuery, """ SELECT "book".* FROM "book" \ JOIN "author" ON "author"."id" = "book"."authorId" \ ORDER BY \ "book"."title" COLLATE swiftLocalizedCaseInsensitiveCompare DESC, \ "author"."lastName" COLLATE swiftLocalizedCaseInsensitiveCompare DESC, \ "author"."firstName" COLLATE swiftLocalizedCaseInsensitiveCompare DESC """) sqlQueries.removeAll() _ /* unorderedBooks */ = try Book .joining(required: Book.author.orderByFullName()) .orderByTitle() .unordered() .fetchAll(db) XCTAssertEqual(lastSQLQuery, """ SELECT "book".* FROM "book" \ JOIN "author" ON "author"."id" = "book"."authorId" """) } } func testSelectionRequest() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in do { sqlQueries.removeAll() let request = Author.all().selectCountry() let authorCountries = try Set(String.fetchAll(db, request)) XCTAssertEqual(authorCountries, ["FR", "US"]) XCTAssertEqual(lastSQLQuery, """ SELECT "country" FROM "author" """) } do { sqlQueries.removeAll() let request = Book.including(required: Book.author.selectCountry()) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, """ SELECT "book".*, "author"."country" \ FROM "book" \ JOIN "author" ON "author"."id" = "book"."authorId" """) } } } func testJoinableRequest() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in do { sqlQueries.removeAll() let frenchBookTitles = try Book.all() .filter(authorCountry: "FR") .order(Column("title")) .fetchAll(db) .map(\.title) XCTAssertEqual(frenchBookTitles, ["Du côté de chez Swann"]) XCTAssertEqual(lastSQLQuery, """ SELECT "book".* \ FROM "book" \ JOIN "author" ON ("author"."id" = "book"."authorId") AND ("author"."country" = 'FR') \ ORDER BY "book"."title" """) } do { sqlQueries.removeAll() let frenchAuthorFullNames = try Author .joining(required: Author.books.filter(authorCountry: "FR")) .order(Column("firstName")) .fetchAll(db) .map(\.fullName) XCTAssertEqual(frenchAuthorFullNames, ["Marcel Proust"]) XCTAssertEqual(lastSQLQuery, """ SELECT "author1".* \ FROM "author" "author1" \ JOIN "book" ON "book"."authorId" = "author1"."id" \ JOIN "author" "author2" ON ("author2"."id" = "book"."authorId") AND ("author2"."country" = 'FR') \ ORDER BY "author1"."firstName" """) } } } func testTableRequestFilteredRequest() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in // filter(id:) do { let title = try Book.all() .filter(id: 2) .fetchOne(db) .map(\.title) XCTAssertEqual(title, "Du côté de chez Swann") XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "book" WHERE "id" = 2 """) let fullName = try Author .joining(required: Author.books.filter(id: 2)) .fetchOne(db) .map(\.fullName) XCTAssertEqual(fullName, "Marcel Proust") XCTAssertEqual(lastSQLQuery, """ SELECT "author".* FROM "author" \ JOIN "book" ON ("book"."authorId" = "author"."id") AND ("book"."id" = 2) \ LIMIT 1 """) } // matchingFts4 do { sqlQueries.removeAll() let title = try Book.all() .matchingFts4(FTS3Pattern(rawPattern: "moby dick")) .fetchOne(db) .map(\.title) XCTAssertEqual(title, "Moby-Dick") XCTAssert(sqlQueries.contains(""" SELECT "book".* FROM "book" \ JOIN "bookFts4" ON ("bookFts4"."rowid" = "book"."id") AND ("bookFts4" MATCH 'moby dick') \ LIMIT 1 """)) sqlQueries.removeAll() let fullName = try Author .joining(required: Author.books.matchingFts4(FTS3Pattern(rawPattern: "moby dick"))) .fetchOne(db) .map(\.fullName) XCTAssertEqual(fullName, "Herman Melville") XCTAssert(sqlQueries.contains(""" SELECT "author".* FROM "author" \ JOIN "book" ON "book"."authorId" = "author"."id" \ JOIN "bookFts4" ON ("bookFts4"."rowid" = "book"."id") AND ("bookFts4" MATCH 'moby dick') \ LIMIT 1 """)) } #if SQLITE_ENABLE_FTS5 // matchingFts5 do { sqlQueries.removeAll() let title = try Book.all() .matchingFts5(FTS3Pattern(rawPattern: "cote swann")) .fetchOne(db) .map(\.title) XCTAssertEqual(title, "Du côté de chez Swann") XCTAssert(sqlQueries.contains(""" SELECT "book".* FROM "book" \ JOIN "bookFts5" ON ("bookFts5"."rowid" = "book"."id") AND ("bookFts5" MATCH 'cote swann') \ LIMIT 1 """)) sqlQueries.removeAll() let fullName = try Author .joining(required: Author.books.matchingFts5(FTS3Pattern(rawPattern: "cote swann"))) .fetchOne(db) .map(\.fullName) XCTAssertEqual(fullName, "Marcel Proust") XCTAssert(sqlQueries.contains(""" SELECT "author".* FROM "author" \ JOIN "book" ON "book"."authorId" = "author"."id" \ JOIN "bookFts5" ON ("bookFts5"."rowid" = "book"."id") AND ("bookFts5" MATCH 'cote swann') \ LIMIT 1 """)) } #endif // orderById do { let titles = try Book.all() .orderById() .fetchAll(db) .map(\.title) XCTAssertEqual(titles, ["Moby-Dick", "Du côté de chez Swann"]) XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "book" ORDER BY "id" """) let fullNames = try Author .joining(required: Author.books.orderById()) .fetchAll(db) .map(\.fullName) XCTAssertEqual(fullNames, ["Herman Melville", "Marcel Proust"]) XCTAssertEqual(lastSQLQuery, """ SELECT "author".* FROM "author" \ JOIN "book" ON "book"."authorId" = "author"."id" ORDER BY "book"."id" """) } } } }
mit
dab6253a1f846fc3fd20bb044442d769
37.764706
118
0.504616
5.187275
false
false
false
false
timgrohmann/vertretungsplan_ios
Vertretungsplan/changedView.swift
1
1366
// // changedView.swift // Vertretungsplan // // Created by Tim Grohmann on 07.09.16. // Copyright © 2016 Tim Grohmann. All rights reserved. // import UIKit class ChangedView: UIView { var connectedToTop = false var connectedToBottom = false // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext()! context.setStrokeColor(UIColor.red.cgColor) context.setFillColor(UIColor.colorFromHex("DC3023")!.cgColor) context.move(to: CGPoint(x: 0, y: 0)) if connectedToTop{ context.addLine(to: CGPoint(x: rect.width, y: 0)) } context.addLine(to: CGPoint(x: rect.width, y: rect.height/2)) if connectedToBottom{ context.addLine(to: CGPoint(x: rect.width, y: rect.height)) } context.addLine(to: CGPoint(x: 0, y: rect.height)) context.addLine(to: CGPoint(x: 0, y: 0)) context.fillPath(); } init(frame: CGRect, top: Bool, bottom: Bool) { super.init(frame: frame) connectedToTop = top connectedToBottom = bottom } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
apache-2.0
de4a6200271956588410c4e41f288b6c
28.042553
78
0.61978
4.0625
false
false
false
false
sschiau/swift
test/stdlib/OSLogPrototypeExecTest.swift
2
18012
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -swift-version 5 -DPTR_SIZE_%target-ptrsize -o %t/OSLogPrototypeExecTest // RUN: %target-run %t/OSLogPrototypeExecTest // REQUIRES: executable_test // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos // Run-time tests for testing the new OS log APIs that accept string // interpolations. The new APIs are still prototypes and must be used only in // tests. import OSLogPrototype import StdlibUnittest defer { runAllTests() } internal var OSLogTestSuite = TestSuite("OSLogTest") if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { // Following tests check whether valid log calls execute without // compile-time and run-time errors. func logMessages(_ h: Logger) { // Test logging of simple messages. h.log("A message with no data") // Test logging at specific levels. h.log(level: .debug, "Minimum integer value: \(Int.min, format: .hex)") h.log(level: .info, "Maximum integer value: \(Int.max, format: .hex)") let privateID = 0x79abcdef h.log( level: .error, "Private Identifier: \(privateID, format: .hex, privacy: .private)") let addr = 0x7afebabe h.log( level: .fault, "Invalid address: 0x\(addr, format: .hex, privacy: .public)") // Test logging with multiple arguments. let filePermissions = 0o777 let pid = 122225 h.log( level: .error, """ Access prevented: process \(pid) initiated by \ user: \(privateID, privacy: .private) attempted resetting \ permissions to \(filePermissions, format: .octal) """) } OSLogTestSuite.test("log with default logger") { let h = Logger() logMessages(h) } OSLogTestSuite.test("log with custom logger") { let h = Logger(subsystem: "com.swift.test", category: "OSLogAPIPrototypeTest") logMessages(h) } OSLogTestSuite.test("escaping of percents") { let h = Logger() h.log("a = c % d") h.log("Process failed after 99% completion") h.log("Double percents: %%") } // A stress test that checks whether the log APIs handle messages with more // than 48 interpolated expressions. Interpolated expressions beyond this // limit must be ignored. OSLogTestSuite.test("messages with too many arguments") { let h = Logger() h.log( level: .error, """ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(48) \(49) """) // The number 49 should not appear in the logged message. } OSLogTestSuite.test("escape characters") { let h = Logger() h.log("\"Imagination is more important than knowledge\" - Einstein") h.log("\'Imagination is more important than knowledge\' - Einstein") h.log("Imagination is more important than knowledge \n - Einstein") h.log("Imagination is more important than knowledge - \\Einstein") h.log("The log message will be truncated here.\0 You won't see this") } OSLogTestSuite.test("unicode characters") { let h = Logger() h.log("dollar sign: \u{24}") h.log("black heart: \u{2665}") h.log("sparkling heart: \u{1F496}") } OSLogTestSuite.test("raw strings") { let h = Logger() let x = 10 h.log(#"There is no \(interpolated) value in this string"#) h.log(#"This is not escaped \n"#) h.log(##"'\b' is a printf escape character but not in Swift"##) h.log(##"The interpolated value is \##(x)"##) h.log(#"Sparkling heart should appear in the next line. \#n \#u{1F496}"#) } OSLogTestSuite.test("integer types") { let h = Logger() h.log("Smallest 32-bit integer value: \(Int32.min, format: .hex)") } OSLogTestSuite.test("dynamic strings") { let h = Logger() let smallString = "a" h.log("A small string: \(smallString, privacy: .public)") let largeString = "This is a large String" h.log("\(largeString, privacy: .public)") let concatString = "hello" + " - " + "world" h.log("A dynamic string: \(concatString, privacy: .public)") let interpolatedString = "\(31) trillion digits of pi are known so far" h.log("\(interpolatedString)") } } // The following tests check the correctness of the format string and the // byte buffer constructed by the APIs from a string interpolation. // These tests do not perform logging and do not require the os_log ABIs to // be available. internal var InterpolationTestSuite = TestSuite("OSLogInterpolationTest") internal let intPrefix = Int.bitWidth == CLongLong.bitWidth ? "ll" : "" internal let bitsPerByte = 8 /// A struct that exposes methods for checking whether a given byte buffer /// conforms to the format expected by the os_log ABI. This struct acts as /// a specification of the byte buffer format. internal struct OSLogBufferChecker { internal let buffer: UnsafeBufferPointer<UInt8> internal init(_ byteBuffer: UnsafeBufferPointer<UInt8>) { buffer = byteBuffer } /// Bit mask for setting bits in the peamble. The bits denoted by the bit /// mask indicate whether there is an argument that is private, and whether /// there is an argument that is non-scalar: String, NSObject or Pointer. internal enum PreambleBitMask: UInt8 { case privateBitMask = 0x1 case nonScalarBitMask = 0x2 } /// Check the summary bytes of the byte buffer. /// - Parameters: /// - argumentCount: number of arguments expected to be in the buffer. /// - hasPrivate: true iff there exists a private argument /// - hasNonScalar: true iff there exists a non-scalar argument internal func checkSummaryBytes( argumentCount: UInt8, hasPrivate: Bool, hasNonScalar: Bool ) { let preamble = buffer[0] let privateBit = preamble & PreambleBitMask.privateBitMask.rawValue expectEqual(hasPrivate, privateBit != 0) let nonScalarBit = preamble & PreambleBitMask.nonScalarBitMask.rawValue expectEqual(hasNonScalar, nonScalarBit != 0) expectEqual(argumentCount, buffer[1]) } /// The possible values for the argument flag as defined by the os_log ABI. /// This occupies four least significant bits of the first byte of the /// argument header. Two least significant bits are used to indicate privacy /// and the other two bits are reserved. internal enum ArgumentFlag: UInt8 { case privateFlag = 0x1 case publicFlag = 0x2 } /// The possible values for the argument type as defined by the os_log ABI. /// This occupies four most significant bits of the first byte of the /// argument header. internal enum ArgumentType: UInt8 { case scalar = 0, count, string, pointer, object // TODO: include wide string and errno here if needed. } /// Check the encoding of an argument in the byte buffer starting from the /// `startIndex`. /// - precondition: `T` must be a type that is accepted by os_log ABI. private func checkArgument<T>( startIndex: Int, size: UInt8, flag: ArgumentFlag, type: ArgumentType, expectedData: T ) { let argumentHeader = buffer[startIndex] expectEqual((type.rawValue << 4) | flag.rawValue, argumentHeader) expectEqual(size, buffer[startIndex + 1]) // Check the payload and diagnose error. Strings are specially handled as // only their addresses are stored in the buffer, and their addresses could // not be compared directly. if !(expectedData is String) { withUnsafeBytes(of: expectedData) { expectedBytes in for i in 0..<Int(size) { // Argument data starts after the two header bytes. expectEqual( expectedBytes[i], buffer[startIndex + 2 + i], "mismatch at byte number \(i) " + "of the expected value \(expectedData)") } } return } // Read the pointer to a string stored in the buffer and compare it with // the expected string using `strcmp`. Note that it is important we use a C // function here to compare the string as it more closely represents the C // os_log functions. var stringAddress: Int = 0 // Copy the bytes of the address byte by byte. Note that // RawPointer.load(fromByteOffset:,_) function cannot be used here as the // address: `buffer + offset` is not aligned for reading an Int. for i in 0..<Int(size) { stringAddress |= Int(buffer[startIndex + 2 + i]) << (8 * i) } let bufferDataPointer = UnsafePointer<Int8>(bitPattern: stringAddress) (expectedData as! String).withCString { let compareResult = strcmp($0, bufferDataPointer) expectEqual(0, compareResult, "strcmp returned \(compareResult)") } } /// Check whether the bytes starting from `startIndex` contain the encoding /// for an Int. internal func checkInt<T>( startIndex: Int, flag: ArgumentFlag, expectedInt: T ) where T : FixedWidthInteger { checkArgument( startIndex: startIndex, size: UInt8(MemoryLayout<T>.size), flag: flag, type: .scalar, expectedData: expectedInt) } /// Check whether the bytes starting from `startIndex` contain the encoding /// for a string. internal func checkString( startIndex: Int, flag: ArgumentFlag, expectedString: String ) { checkArgument( startIndex: startIndex, size: UInt8(MemoryLayout<UnsafePointer<Int8>>.size), flag: flag, type: .string, expectedData: expectedString) } /// Check the given assertions on the arguments stored in the byte buffer. /// - Parameters: /// - assertions: one assertion for each argument stored in the byte buffer. internal func checkArguments(_ assertions: [(Int) -> Void]) { var currentArgumentIndex = 2 for assertion in assertions { expectTrue(currentArgumentIndex < buffer.count) assertion(currentArgumentIndex) // Advance the index to the next argument by adding the size of the // current argument and the two bytes of headers. currentArgumentIndex += 2 + Int(buffer[currentArgumentIndex + 1]) } } /// Check a sequence of assertions on the arguments stored in the byte buffer. internal func checkArguments(_ assertions: (Int) -> Void ...) { checkArguments(assertions) } } InterpolationTestSuite.test("integer literal") { _checkFormatStringAndBuffer( "An integer literal \(10)", with: { (formatString, buffer) in expectEqual( "An integer literal %{public}\(intPrefix)d", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt(startIndex: $0, flag: .publicFlag, expectedInt: 10) }) }) } InterpolationTestSuite.test("integer with formatting") { _checkFormatStringAndBuffer( "Minimum integer value: \(Int.min, format: .hex)", with: { (formatString, buffer) in expectEqual( "Minimum integer value: %{public}\(intPrefix)x", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt( startIndex: $0, flag: .publicFlag, expectedInt: Int.min) }) }) } InterpolationTestSuite.test("integer with privacy and formatting") { let addr = 0x7afebabe _checkFormatStringAndBuffer( "Access to invalid address: \(addr, format: .hex, privacy: .private)", with: { (formatString, buffer) in expectEqual( "Access to invalid address: %{private}\(intPrefix)x", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: true, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt( startIndex: $0, flag: .privateFlag, expectedInt: addr) }) }) } InterpolationTestSuite.test("integer with privacy and formatting") { let addr = 0x7afebabe _checkFormatStringAndBuffer( "Access to invalid address: \(addr, format: .hex, privacy: .private)", with: { (formatString, buffer) in expectEqual( "Access to invalid address: %{private}\(intPrefix)x", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: true, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt( startIndex: $0, flag: .privateFlag, expectedInt: addr) }) }) } InterpolationTestSuite.test("test multiple arguments") { let filePerms = 0o777 let pid = 122225 let privateID = 0x79abcdef _checkFormatStringAndBuffer( """ Access prevented: process \(pid) initiated by \ user: \(privateID, privacy: .private) attempted resetting \ permissions to \(filePerms, format: .octal) """, with: { (formatString, buffer) in expectEqual( """ Access prevented: process %{public}\(intPrefix)d initiated by \ user: %{private}\(intPrefix)d attempted resetting permissions \ to %{public}\(intPrefix)o """, formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 3, hasPrivate: true, hasNonScalar: false) bufferChecker.checkArguments( { bufferChecker.checkInt( startIndex: $0, flag: .publicFlag, expectedInt: pid) }, { bufferChecker.checkInt( startIndex: $0, flag: .privateFlag, expectedInt: privateID) }, { bufferChecker.checkInt( startIndex: $0, flag: .publicFlag, expectedInt: filePerms) }) }) } InterpolationTestSuite.test("interpolation of too many arguments") { // The following string interpolation has 49 interpolated values. Only 48 // of these must be present in the generated format string and byte buffer. _checkFormatStringAndBuffer( """ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) """, with: { (formatString, buffer) in expectEqual( String( repeating: "%{public}\(intPrefix)d ", count: Int(maxOSLogArgumentCount)), formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: maxOSLogArgumentCount, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments( Array( repeating: { bufferChecker.checkInt( startIndex: $0, flag: .publicFlag, expectedInt: 1) }, count: Int(maxOSLogArgumentCount)) ) }) } InterpolationTestSuite.test("string interpolations with percents") { _checkFormatStringAndBuffer( "a = (c % d)%%", with: { (formatString, buffer) in expectEqual("a = (c %% d)%%%%", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 0, hasPrivate: false, hasNonScalar: false) }) } InterpolationTestSuite.test("integer types") { _checkFormatStringAndBuffer("Int32 max: \(Int32.max)") { (formatString, buffer) in expectEqual("Int32 max: %{public}d", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt( startIndex: $0, flag: .publicFlag, expectedInt: Int32.max) }) } } InterpolationTestSuite.test("string arguments") { let small = "a" let large = "this is a large string" _checkFormatStringAndBuffer( """ small: \(small, privacy: .public) \ large: \(large, privacy: .private) """) { (formatString, buffer) in expectEqual("small: %{public}s large: %{private}s", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 2, hasPrivate: true, hasNonScalar: true ) bufferChecker.checkArguments({ bufferChecker.checkString( startIndex: $0, flag: .publicFlag, expectedString: small) }, { bufferChecker.checkString( startIndex: $0, flag: .privateFlag, expectedString: large) }) } } InterpolationTestSuite.test("dynamic strings") { let concatString = "hello" + " - " + "world" let interpolatedString = "\(31) trillion digits of pi are known so far" _checkFormatStringAndBuffer( """ concat: \(concatString, privacy: .public) \ interpolated: \(interpolatedString, privacy: .private) """) { (formatString, buffer) in expectEqual("concat: %{public}s interpolated: %{private}s", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 2, hasPrivate: true, hasNonScalar: true ) bufferChecker.checkArguments({ bufferChecker.checkString( startIndex: $0, flag: .publicFlag, expectedString: concatString) }, { bufferChecker.checkString( startIndex: $0, flag: .privateFlag, expectedString: interpolatedString) }) } }
apache-2.0
9c08aa9231a61b2aba6b002d45e2ea85
30.379791
103
0.641017
4.277369
false
true
false
false
gpancio/iOS-Prototypes
VehicleID/Example/VehicleID/IdentifyVehicleViewController.swift
1
5513
// // IdentifyVehicleViewController.swift // TestAudaToolkitPod // import UIKit import GPUIKit import VehicleID import EdmundsAPI import MBProgressHUD class IdentifyVehicleViewController: ATViewController, ScanVINViewControllerDelegate, VINDecoderDelegate { var vehicle: Vehicle? { didSet { if vehicle != nil { addNextButton() } else { nextButton?.hidden = true } } } var progressHud: MBProgressHUD? private var vin: String? func addNextButton() { guard vehicle != nil else { return } if !vehicle!.availablePackages.isEmpty { nextButton?.setTitle("Next: Select a Package", forState: .Normal) } else if !vehicle!.options.isEmpty { nextButton?.setTitle("Next: Select Options", forState: .Normal) } nextButton?.hidden = false } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. nextButton?.hidden = true if vehicle != nil { nextButton?.hidden = false } } // MARK: - ScanVINViewControllerDelegate func vinScanned(vin: String) { self.vin = vin self.vehicle = nil startVINDecode(vin) } // MARK: VIN Decoding func startVINDecode(vin: String) { progressHud = MBProgressHUD.showHUDAddedTo(view, animated: true) progressHud?.labelText = "Decoding VIN..." var decoder = createVINDecoder() decoder.vinDelegate = self decoder.decodeVIN(vin) } func vinDecodeSuccess(vehicle: Vehicle) { dispatch_async(dispatch_get_main_queue()) { MBProgressHUD.hideHUDForView(self.view, animated: true) } showConfirmDialog(vehicle) } func vinDecodeFailed(reason: VINDecodeFailureReason) { dispatch_async(dispatch_get_main_queue()) { MBProgressHUD.hideHUDForView(self.view, animated: true) } switch reason { case .InvalidVIN: showErrorAlert("Failed to decode VIN: invalid VIN") vehicle = nil break case .ServiceNotAvailable: showErrorAlert("Failed to decode VIN: service unavailable") break } } func showConfirmDialog(vehicle: Vehicle) { let alertController = UIAlertController(title: vehicle.yearMakeModel, message: "Is this your vehicle?", preferredStyle: UIAlertControllerStyle.Alert) let nopeAction = UIAlertAction(title: "Nope!", style: .Cancel) { (action) in self.vehicle = nil } alertController.addAction(nopeAction) let yupAction = UIAlertAction(title: "Yes!", style: .Default) { (action) in self.vehicle = vehicle } alertController.addAction(yupAction) self.presentViewController(alertController, animated: true, completion: nil) } class OfflineDataProvider: DataProvider { var validSet: [String] init(validSet: [String]) { self.validSet = validSet } func fetchData(dataMap: DataMap, completion: [String] -> Void, error: (String -> Void)? ) { completion(validSet) } } func createDataMap() -> DataMap { let dataMap = DataMap() var makeDataProvider: DataProvider var modelDataProvider: DataProvider var styleDataProvider: DataProvider let userDefaults = NSUserDefaults.standardUserDefaults() if userDefaults.boolForKey("offline") { makeDataProvider = OfflineDataProvider(validSet: ["Acura", "Audi", "BMW", "Buick", "Cadillac", "Honda", "Toyota"]) modelDataProvider = OfflineDataProvider(validSet: ["Civic", "CRV", "Odyssey", "Pilot"]) styleDataProvider = OfflineDataProvider(validSet: ["EX", "GX", "LX"]) } else { makeDataProvider = VehicleMakesDataProvider() modelDataProvider = VehicleModelsDataProvider() styleDataProvider = VehicleStylesDataProvider() } let years = (1970...(NSCalendar.getCurrentYear()+1)).map() { return "\($0)"} let yearDataSet = DataSet(validSet: years.reverse()) dataMap[Key.Year] = yearDataSet let makeDataSet = DataSet(dataProvider: makeDataProvider) makeDataSet.observe(yearDataSet) dataMap[Key.Make] = makeDataSet let modelDataSet = DataSet(dataProvider: modelDataProvider) modelDataSet.observe(makeDataSet) dataMap[Key.Model] = modelDataSet let styleDataSet = DataSet(dataProvider: styleDataProvider) styleDataSet.observe(modelDataSet) dataMap[Key.Style] = styleDataSet return dataMap } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "scanVIN" { if let vc = segue.destinationViewController as? ScanVINViewController { vc.delegate = self } } else if segue.identifier == "selectVehicleEmbed" { if let vc = segue.destinationViewController as? IdentifyVehicleTableViewController { vc.rootViewController = self vc.dataMap = createDataMap() } } } }
mit
54ac4cc5d1666386755e2f9db335e3f8
31.621302
157
0.601125
5.142724
false
false
false
false
CM-Studio/NotLonely-iOS
NotLonely-iOS/ViewController/Navi/NLNavigationController.swift
1
1410
// // NLNavigationController.swift // NotLonely-iOS // // Created by plusub on 4/5/16. // Copyright © 2016 cm. All rights reserved. // import UIKit class NLNavigationController: UINavigationController { var animatedOnNavigationBar = true override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // guard let navigationController = navigationController else { // return // } self.navigationBar.barTintColor = UIColor.NLMainColor() self.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.navigationBar.backgroundColor = nil self.navigationBar.translucent = true self.navigationBar.shadowImage = nil self.navigationBar.barStyle = UIBarStyle.Default self.navigationBar.setBackgroundImage(nil, forBarMetrics: UIBarMetrics.Default) self.navigationBar.tintColor = nil if self.navigationBarHidden { self.setNavigationBarHidden(false, animated: animatedOnNavigationBar) } } }
mit
5cf0a3cc24ff4e079890cd61060adc74
27.755102
103
0.66785
5.440154
false
false
false
false
guillermo-ag-95/App-Development-with-Swift-for-Students
1 - Getting Started/4 - Control Flow/lab/Lab - Control Flow.playground/Pages/2. Exercise - If and If-Else Statements.xcplaygroundpage/Contents.swift
1
1475
/*: ## Exercise - If and If-Else Statements Imagine you're creating a machine that will count your money for you and tell you how wealthy you are based on how much money you have. A variable `dollars` has been given to you with a value of 0. Write an if statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0. Observe what is printed to the console. */ var dollars = 0 if dollars == 0 { print("Sorry, kid. You're broke!") } /*: `dollars` has been updated below to have a value of 10. Write an an if-else statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0, but prints "You've got some spending money!" otherwise. Observe what is printed to the console. */ dollars = 10 if dollars == 0 { print("Sorry, kid. You're broke!") } else { print("You've got some spending money!") } /*: `dollars` has been updated below to have a value of 105. Write an an if-else-if statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0, prints "You've got some spending money!" if `dollars` is less than 100, and prints "Looks to me like you're rich!" otherwise. Observe what is printed to the console. */ dollars = 105 if dollars == 0 { print("Sorry, kid. You're broke!") } else if dollars < 100 { print("You've got some spending money!") } else { print("Looks to me like you're rich!") } //: [Previous](@previous) | page 2 of 9 | [Next: App Exercise - Fitness Decisions](@next)
mit
be9aef1aa8d1dc3f4f81cfb453196b8d
43.69697
331
0.687458
3.715365
false
false
false
false
pdcgomes/RendezVous
Vendor/docopt/Tokens.swift
1
1397
// // Tokens.swift // docopt // // Created by Pavel S. Mazurin on 3/1/15. // Copyright (c) 2015 kovpas. All rights reserved. // import Foundation internal class Tokens: Equatable, CustomStringConvertible { private var tokensArray: [String] var error: DocoptError var description: String { get { return " ".join(tokensArray) } } convenience init(_ source: String, error: DocoptError = DocoptExit()) { self.init(source.split(), error: error) } init(_ source: [String], error: DocoptError = DocoptExit() ) { tokensArray = source self.error = error } static func fromPattern(source: String) -> Tokens { let res = source.stringByReplacingOccurrencesOfString("([\\[\\]\\(\\)\\|]|\\.\\.\\.)", withString: " $1 ", options: .RegularExpressionSearch) let result = res.split("\\s+|(\\S*<.*?>)").filter { !$0.isEmpty } return Tokens(result, error: DocoptLanguageError()) } func current() -> String? { if tokensArray.isEmpty { return nil } return tokensArray[0] } func move() -> String? { if tokensArray.isEmpty { return nil } return tokensArray.removeAtIndex(0) } } func ==(lhs: Tokens, rhs: Tokens) -> Bool { return lhs.tokensArray == rhs.tokensArray }
mit
b3fce7fc3b960ce2805598f3ace9e37e
24.4
149
0.569077
4.365625
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCardPayment/Sources/FeatureCardPaymentDomain/Services/ApplePayAuthorizationService.swift
1
5190
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import Foundation import PassKit final class ApplePayAuthorizationService: NSObject, ApplePayAuthorizationServiceAPI { private var paymentAuthorizationController: PKPaymentAuthorizationController? private var tokenSubject = PassthroughSubject<Result<ApplePayToken, ApplePayError>, Never>() func getToken( amount: Decimal, currencyCode: String, info: ApplePayInfo ) -> AnyPublisher<ApplePayToken, ApplePayError> { tokenSubject = PassthroughSubject<Result<ApplePayToken, ApplePayError>, Never>() return tokenSubject .handleEvents(receiveSubscription: { [weak self] _ in guard let self = self else { return } var requiredBillingContactFields: Set<PKContactField>? { guard let fields = info.requiredBillingContactFields, fields.isNotEmpty else { return nil } return Set(fields.map(PKContactField.init(rawValue:))) } var supportedNetworks: [PKPaymentNetwork] { guard let networks = info.supportedNetworks, networks.isNotEmpty else { return [.visa, .masterCard] } return networks.compactMap(PKPaymentNetwork.init(rawValue:)) } let paymentAuthorizationController = paymentController( request: paymentRequest( amount: amount, currencyCode: currencyCode, info: info, requiredBillingContactFields: requiredBillingContactFields, supportedCountries: info.supportedCountries.isNilOrEmpty ? nil : info.supportedCountries.map(Set.init), supportedNetworks: supportedNetworks ), delegate: self ) paymentAuthorizationController.present(completion: { [weak self] presented in guard !presented else { return } self?.tokenSubject.send(.failure(.invalidInputParameters)) }) self.paymentAuthorizationController = paymentAuthorizationController }) .flatMap { result -> AnyPublisher<ApplePayToken, ApplePayError> in result.publisher.eraseToAnyPublisher() } .first() .eraseToAnyPublisher() } } private func paymentController( request: PKPaymentRequest, delegate: PKPaymentAuthorizationControllerDelegate ) -> PKPaymentAuthorizationController { let controller = PKPaymentAuthorizationController( paymentRequest: request ) controller.delegate = delegate return controller } // swiftlint:disable function_parameter_count private func paymentRequest( amount: Decimal, currencyCode: String, info: ApplePayInfo, requiredBillingContactFields: Set<PKContactField>?, supportedCountries: Set<String>?, supportedNetworks: [PKPaymentNetwork]? ) -> PKPaymentRequest { let paymentRequest = PKPaymentRequest() paymentRequest.currencyCode = currencyCode paymentRequest.countryCode = info.merchantBankCountryCode paymentRequest.merchantIdentifier = info.applePayMerchantID requiredBillingContactFields.map { paymentRequest.requiredBillingContactFields = $0 } supportedNetworks.map { paymentRequest.supportedNetworks = $0 } supportedCountries.map { paymentRequest.supportedCountries = $0 } paymentRequest.merchantCapabilities = info.capabilities paymentRequest.paymentSummaryItems = [ PKPaymentSummaryItem( label: "Blockchain.com", amount: amount as NSDecimalNumber ) ] return paymentRequest } extension ApplePayAuthorizationService: PKPaymentAuthorizationControllerDelegate { func paymentAuthorizationControllerDidFinish(_ controller: PKPaymentAuthorizationController) { controller.dismiss { [tokenSubject] in tokenSubject.send(.failure(.cancelled)) } } func paymentAuthorizationController( _ controller: PKPaymentAuthorizationController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void ) { guard let token = ApplePayToken(token: payment.token, billingContact: payment.billingContact) else { completion(.init(status: .failure, errors: [ApplePayError.invalidTokenParameters])) tokenSubject.send(.failure(.invalidTokenParameters)) return } tokenSubject.send(.success(token)) completion(.init(status: .success, errors: nil)) } } extension ApplePayInfo { var capabilities: PKMerchantCapability { guard let allowCreditCards = allowCreditCards, allowCreditCards else { return [.capability3DS, .capabilityDebit] } return [.capability3DS, .capabilityDebit, .capabilityCredit] } }
lgpl-3.0
7e6f7972b68b334377fb319648206ba4
38.015038
108
0.652149
6.192124
false
false
false
false
rporzuc/FindFriends
FindFriends/FindFriends/PeopleNearby/PeopleNearbyTableViewController.swift
1
11488
import UIKit import CoreLocation class PeopleNearbyTableViewController: UITableViewController { var selectedIndexPath : IndexPath? = nil struct person { var idPerson : Int64? var firstName : String? var lastName : String? var imagePerson : NSData? } var arrayPerson : [person] = [] func prepareArray(){ let locationManager = CLLocationManager() locationManager.requestAlwaysAuthorization() if CLLocationManager.locationServicesEnabled() { if locationManager.location != nil { let userLocation : CLLocation = locationManager.location! as CLLocation let longitude = String(userLocation.coordinate.longitude) let latitude = String(userLocation.coordinate.latitude) let connectionToServer = ConnectionToServer.shared connectionToServer.peopleNearby(longitude: longitude, latitude: latitude, completion: { (bool) in if bool == true { self.getPeopleNearby() }else{ self.refreshControl?.endRefreshing() } }) } } } func getPeopleNearby(){ DispatchQueue.global(qos: .background).async { DataManagement.shared.getPeopleNearby(completion: { (array) in self.arrayPerson.removeAll() for i in 0..<array.count { self.arrayPerson.append(person(idPerson: array[i].idPerson, firstName: array[i].firstName, lastName: array[i].lastName, imagePerson: array[i].imagePerson)) } DispatchQueue.main.async { self.disableTheSelectionMode() self.tableView.reloadData() self.refreshControl?.endRefreshing() } }) } } override func viewDidLoad() { super.viewDidLoad() prepareArray() let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(PeopleNearbyTableViewController.prepareArray), for: UIControlEvents.valueChanged) self.refreshControl = refreshControl } override func viewWillAppear(_ animated: Bool) { if selectedIndexPath != nil { tableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: UITableViewScrollPosition.none) } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayPerson.count == 0 ? 1 : arrayPerson.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if arrayPerson.count == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "basicCell", for: indexPath) cell.textLabel?.text = "Sorry, you don't have any friends nearby." return cell }else { let cell = tableView.dequeueReusableCell(withIdentifier: "customCellPeopleNearby", for: indexPath) as! PeopleNearbyCustomTableViewCell if arrayPerson[indexPath.row].imagePerson != nil{ cell.imagePerson.image = UIImage(data: arrayPerson[indexPath.row].imagePerson as! Data) } cell.labelFirstName.text = arrayPerson[indexPath.row].firstName cell.labelLastName.text = arrayPerson[indexPath.row].lastName cell.imagePerson.layer.cornerRadius = cell.imagePerson.layer.frame.width / 2 cell.imagePerson.layer.masksToBounds = true if cell.isSelected == true { cell.btnSendMessage.isHidden = false cell.btnShowContactOnMap.isHidden = false }else { cell.btnSendMessage.isHidden = true cell.btnShowContactOnMap.isHidden = true } cell.btnShowContactOnMap.addTarget(self, action: #selector(self.btnShowContactOnMapClicked), for: UIControlEvents.touchUpInside) cell.btnSendMessage.addTarget(self, action: #selector(self.btnSendMessageClicked), for: UIControlEvents.touchUpInside) let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action:#selector(self.enableTheSelectionMode(sender:))) longPressGestureRecognizer.minimumPressDuration = 1.0 cell.addGestureRecognizer(longPressGestureRecognizer) return cell } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "People Nearby" } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 45 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if selectionMode{ let view = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.width, height: 45)) view.backgroundColor = UIColor.groupTableViewBackground let buttonCancel = UIButton(frame: CGRect(x: 5, y: 5, width: 35, height: 35)) buttonCancel.setImage(UIImage(named: "ImageDelete"), for: .normal) buttonCancel.addTarget(self, action: #selector(self.disableTheSelectionMode), for: .touchUpInside) view.addSubview(buttonCancel) let buttonMessage = UIButton(frame: CGRect(x: view.frame.width - 40 , y: 5, width: 35, height: 35)) buttonMessage.setImage(UIImage(named: "ImageMessage"), for: .normal) buttonMessage.addTarget(self, action: #selector(self.sendMessagesToSelectedPeople), for: .touchUpInside) view.addSubview(buttonMessage) let label = UILabel(frame: CGRect(x: 45.0, y: 5.0, width: buttonMessage.frame.origin.x - 50, height: 35)) label.text = "Selected: \(arraySelectedIndexPath.count)" view.addSubview(label) return view }else{ return nil } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 90 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if arrayPerson.count != 0 { let cell = tableView.cellForRow(at: indexPath) as! PeopleNearbyCustomTableViewCell selectedIndexPath = indexPath if selectionMode{ if cell.accessoryType == UITableViewCellAccessoryType.checkmark{ cell.accessoryType = .none if let arrayIndex = arraySelectedIndexPath.index(of: indexPath){ arraySelectedIndexPath.remove(at: arrayIndex) } if arraySelectedIndexPath.count == 0{ self.disableTheSelectionMode() } }else{ cell.accessoryType = .checkmark arraySelectedIndexPath.append(indexPath) } self.tableView.reloadData() }else{ cell.btnSendMessage.isHidden = false cell.btnShowContactOnMap.isHidden = false } } } override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if arrayPerson.count != 0 { if let cell = tableView.cellForRow(at: indexPath) as? PeopleNearbyCustomTableViewCell{ cell.btnSendMessage.isHidden = true cell.btnShowContactOnMap.isHidden = true } } } //MARK: - Action on btnShowContactOnMap and btnSendMessage clicked func btnShowContactOnMapClicked() { let parentView = self.parent as! PeopleNearbyViewController let id = Int( arrayPerson[(self.selectedIndexPath?.row)!].idPerson!) parentView.performSegue(withIdentifier: "segueMapViewController", sender: id) } func btnSendMessageClicked() { let parentView = self.parent as! PeopleNearbyViewController let id = Int( arrayPerson[(self.selectedIndexPath?.row)!].idPerson!) parentView.showMessagesView(id_converser: id) } //MARK: - Selection Mode Settings var arraySelectedIndexPath : [IndexPath] = [] var selectionMode : Bool = false func enableTheSelectionMode(sender : UILongPressGestureRecognizer){ if sender.state == .began && !selectionMode{ selectionMode = true print("enable") if selectedIndexPath != nil{ if let previousCell = self.tableView.cellForRow(at: selectedIndexPath!) as? PeopleNearbyCustomTableViewCell{ previousCell.btnSendMessage.isHidden = true previousCell.btnShowContactOnMap.isHidden = true } } let touchPoint = sender.location(in: self.tableView) if let indexPath = tableView.indexPathForRow(at: touchPoint){ tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) arraySelectedIndexPath.append(indexPath) if let cell = tableView.cellForRow(at: indexPath) as? PeopleNearbyCustomTableViewCell{ cell.btnSendMessage.isHidden = true cell.btnShowContactOnMap.isHidden = true cell.accessoryType = .checkmark } } self.tableView.reloadData() } } func disableTheSelectionMode(){ selectionMode = false self.tableView.reloadData() arraySelectedIndexPath.removeAll() for index in 0..<tableView.numberOfRows(inSection: 0){ let cell = tableView.cellForRow(at: IndexPath(row: index, section: 0)) cell?.accessoryType = .none } } func sendMessagesToSelectedPeople(){ let groupMessagesViewController = storyboard?.instantiateViewController(withIdentifier: "groupMessagesViewController") as! GroupMessagesViewController var array : [Int] = [] for index in arraySelectedIndexPath{ array.append(Int(arrayPerson[index.row].idPerson!)) } groupMessagesViewController.arrayPeople = array groupMessagesViewController.delegatePeopleNearbyTableVC = self groupMessagesViewController.modalPresentationStyle = .overCurrentContext self.present(groupMessagesViewController, animated: true, completion: nil) } }
gpl-3.0
44ba008c267be98b780e6f4701bff740
39.027875
175
0.59227
6.024122
false
false
false
false
a2/ErnstHartert
Sources/RegularExpressions.swift
1
1380
import Foundation private let whitespace = "\\s+?" private let optionalWhitespace = "\\s*?" let allTestsDeclaration: NSRegularExpression = { let parensOrVoid = "(?:\\(\\s*?\\)|Void)" let pattern = [ "(?:var|let)", whitespace, "allTests", optionalWhitespace, ":", optionalWhitespace, "\\[", optionalWhitespace, "\\(", optionalWhitespace, "String", optionalWhitespace, ",", optionalWhitespace, parensOrVoid, optionalWhitespace, "->", optionalWhitespace, parensOrVoid, optionalWhitespace, "\\)", optionalWhitespace, "\\]", ].joinWithSeparator("") return try! NSRegularExpression(pattern: pattern, options: []) }() let testFuncDeclaration: NSRegularExpression = { let pattern = [ "func", whitespace, "(test\\w*?)", "\\(\\)", ].joinWithSeparator("") return try! NSRegularExpression(pattern: pattern, options: []) }() let classNameDeclaration: NSRegularExpression = { let pattern = [ "class", whitespace, "(\\S+?)", optionalWhitespace, ":", optionalWhitespace, "XCTestCase", ].joinWithSeparator("") return try! NSRegularExpression(pattern: pattern, options: []) }()
mit
751d8e04a449193789172bd72c10baab
23.210526
70
0.545652
5.348837
false
true
false
false
aestesis/Aether
Sources/Aether/Foundation/Node.swift
1
22587
// // Node.swift // Aether // // Created by renan jegouzo on 22/02/2016. // Copyright © 2016 aestesis. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation #if os(Linux) import Dispatch import Glibc #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// open class Hash : Hashable { public var hashValue: Int { return ObjectIdentifier(self).hashValue } } public func ==(lhs: Hash, rhs: Hash) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// open class Atom: Hash,CustomStringConvertible { ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public var description : String { let m=Swift.Mirror(reflecting: self) let name=String(describing:m.subjectType) return "{ class:\(name) }" } #if DEBUG var dbgdesc:String? = nil public var debugDescription : String { if let dd = dbgdesc { return dd } else { let dd = self.className+".init():\r\n"+Thread.callstack.joined(separator:"\r\n") dbgdesc = dd return dd } } #endif public var className : String { let m=Swift.Mirror(reflecting: self) return String(describing:m.subjectType) } public func wait(_ duration:Double, _ fn:(()->())? = nil) -> Future { return Atom.wait(duration,fn) } public static func wait(_ duration:Double, _ fn:(()->())? = nil) -> Future { let fut=Future() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(duration*Double(Misc.clocksPerSeconds))) / Double(Misc.clocksPerSeconds), execute: { fut.done() }) if let fn = fn { fut.then { f in fn() } } return fut } public func main(fn:@escaping ()->()) { DispatchQueue.main.async { fn() } } public static func main(fn:@escaping ()->()) { DispatchQueue.main.async { fn() } } public func pulse(_ period:Double,_ tick:@escaping ()->()) -> Future { let fut=Future() wait(0).then { f in let t = Timer(period:period,tick:tick) fut["timer"]=t fut.onCancel { (p) in t.stop() fut["timer"]=nil } } return fut } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// #if DEBUG private static var inspect:[String]=[] // ex: "Bitmap" "Future" private static let lock=Lock() private static var dbg=[String:Int]() private static var log=[String:Int]() #endif public static func debugInfo() { #if DEBUG let keys = Array(dbg.keys).sorted() for k in keys { Debug.info("\(k) ... \(dbg[k]!)") } var log=[(count:Int,message:String)]() for d in Atom.log { if d.1 > 10 { log.append((count:d.1,message:d.0)) } } log.sort(by: { (a, b) -> Bool in return a.count > b.count }) for l in log { Debug.info("\(l.count) -> \(l.message)") } #endif } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public override init() { super.init() #if DEBUG Atom.lock.synced { if let c = Atom.dbg[self.className] { Atom.dbg[self.className] = c+1 } else { Atom.dbg[self.className] = 1 } } if Atom.inspect.contains(self.className) { let dbg = self.debugDescription if let n = Atom.log[dbg] { Atom.log[dbg] = n + 1 } else { Atom.log[dbg] = 1 } } #endif } deinit { #if DEBUG Atom.lock.synced { if let c = Atom.dbg[self.className] { Atom.dbg[self.className] = c-1 } if Atom.inspect.contains(self.className) { let dbg = self.debugDescription if let l = Atom.log[dbg] { let n = l - 1 if n == 0 { Atom.log.removeValue(forKey:dbg) } else { Atom.log[dbg] = n } } else { //Debug.error("error") } } } #endif } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public class Classes { var keys=[String]() public func append(key:String) { if(!keys.contains(key)) { keys.append(key) } } public func append(keys:[String]) { for k in keys { self.append(key:k) } } public func append(classes:Classes) { self.append(keys: classes.keys) } public func remove(key:String) { if let i=keys.index(of: key) { keys.remove(at: i) } } public func remove(keys:[String]) { for k in keys { self.remove(key:k) } } public func remove(classes:Classes) { self.remove(keys: classes.keys); } public func contains(key:String) -> Bool { return keys.contains(key) } public func contains(keys:[String]) -> Bool { for k in keys { if !keys.contains(k) { return false } } return true } public func contains(classes:Classes) -> Bool { return self.contains(keys:classes.keys) } public init() { } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// open class Node:Atom { ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public let onDetach=Event<Void>() ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// var prop:[String:Any]=[String:Any]() public private(set) var classes=Classes() public var parent: Node? ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public init(parent: Node?) { super.init() self.parent=parent } ////////////////////////////////////////////////////////////////////////////////////////////////////////// public var attached : Bool { return self.parent != nil } public func detach() { onDetach.dispatch(()) onDetach.removeAll() self.parent = nil for p in prop.values { if let p=p as? Node, p != self && p.parent != nil { p.detach() } } prop.removeAll() } deinit { if self.parent != nil { self.detach() } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public func ancestor<T>() -> T? { if let s = self.parent { if let v=s as? T { return v } else { let v:T? = s.ancestor() return v } } return nil } ////////////////////////////////////////////////////////////////////////////////////////////////////////// public subscript(k:String) -> Any? { get { if let v=prop[k] { if let p = v as? Property { return p.value } return v } if let p=parent { return p[k] } return nil } set(v) { if let p=prop[k] as? Node { if let p = p as? Property { p.value = v return } else if let pv = v as? Node { if pv != p { p.detach() } } else { p.detach() } } prop[k]=v } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// open class Property : Node { public let onGetValue=Event<Any?>() var _value:Any? public var value : Any? { get { onGetValue.dispatch(_value) return _value } set(v) { if let p = _value as? Node { p.detach() } _value = v } } public init() { self._value = nil super.init(parent:nil) } public init(value:Any) { self._value = value super.init(parent:nil) } override public func detach() { if let p = self.value as? Node { p.detach() } super.detach() } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// open class NodeUI : Node { public var viewport:Viewport? { if let v=self as? Viewport { return v } else if let p=parent as? NodeUI { return p.viewport } return nil } public override var attached : Bool { return self.viewport != nil } public func animate(_ duration:Double,_ anime:@escaping (Double)->()) -> Future { let fut=Future(context:"animation") let start=ß.time if let vp=viewport { var a : Action<Void>? = nil a = vp.pulse.always { let t=(ß.time-start)/duration if t<1 { anime(t) fut.progress(t) } else { vp.pulse.remove(a!) anime(1) fut.done() a = nil } } fut.onCancel { p in vp.pulse.remove(a!) a = nil } } return fut } public override func wait(_ duration:Double,_ fn:(()->())? = nil) -> Future { let fut=Future(context:"wait") if duration == 0 { self.ui { fut.done() } } else { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(duration*Double(ß.clocksPerSeconds))) / Double(ß.clocksPerSeconds), execute: { [weak self] in if let this=self, this.attached { this.ui { fut.done() } } else { fut.detach() } }) } if let fn=fn { fut.then { f in fn() } } return fut } public func ui(_ fn:@escaping ()->()) { viewport?.pulse.once { [weak self] in if let this=self, this.attached { fn() } } } public func sui(_ fn:@escaping ()->()) { if let isui = Thread.current["ui.thread"] as? Bool { if isui { fn() } else { self.ui(fn) } } } public func urgent(_ info:String="",_ fn:@escaping ()->()) { if let vp=viewport { let _ = vp.bg.run(self,priority:Job.Priority.high,info:info,action:fn) } } public func bg(_ info:String="",_ fn:@escaping ()->()) { if let vp=viewport { let _ = vp.bg.run(self,info:info,action:fn) } } public func io(_ info:String="",_ fn:@escaping ()->()) { if let vp=viewport { let _ = vp.io.run(self,info:info,action:fn) } } public func zz(_ info:String="",_ fn:@escaping ()->()) { if let vp=viewport { let _ = vp.zz.run(self,info:info,action:fn) } } public init(parent:NodeUI?) { super.init(parent:parent) } open override func detach() { let viewport = self.viewport super.detach() if let viewport = viewport, viewport != self { viewport.clean(self) } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public class Action<T> : Hash { let fn:((T)->())? public func invoke(_ p:T) { fn?(p); } public init(_ fn:@escaping ((T)->())) { self.fn = fn } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public class MultiEvent<T> { private var actions = [String:Set<Action<T>>]() private var onces = [String:Set<Action<T>>]() public func always(_ message:String,action:@escaping (T)->()) { if actions[message] != nil { actions[message]!.insert(Action<T>(action)) } else { actions[message]=Set<Action<T>>() actions[message]!.insert(Action<T>(action)) } } public func once(_ message:String,action:@escaping (T)->()) { if onces[message] != nil { actions[message]!.insert(Action<T>(action)) } else { onces[message]=Set<Action<T>>() onces[message]!.insert(Action<T>(action)) } } public func alive(_ owner:NodeUI,message:String,action:@escaping (T)->()) { let a=Action<T>(action) if actions[message] != nil { actions[message]!.insert(a) } else { actions[message]=Set<Action<T>>() actions[message]!.insert(a) } owner.onDetach.once({ self.actions[message]!.remove(a) }) } public func dispatch(_ message:String,_ p:T) { if let ac=actions[message] { for a in ac { a.invoke(p); } } if let o=onces[message] { onces[message]=Set<Action<T>>() for a in o { a.invoke(p) } } } public init() { } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public class Event<T> { private var actions = Set<Action<T>>() private var onces = Set<Action<T>>() private let lock=Lock() public func Event() { } public func always(_ action: @escaping (T)->()) -> Action<T> { let a=Action<T>(action) lock.synced { self.actions.insert(a) } return a } public func once(_ action: @escaping (T)->()) { lock.synced { self.onces.insert(Action<T>(action)) } } public func alive(_ owner: Node, _ action: @escaping (T)->()) { let a=Action<T>(action) lock.synced { self.actions.insert(a); } owner.onDetach.once { self.lock.synced { self.actions.remove(a) } } } public var count:Int { return actions.count+onces.count } public func dispatch(_ p:T) { var ac:Set<Action<T>>? var o:Set<Action<T>>? lock.synced { ac = self.actions o = self.onces self.onces.removeAll() } for a in ac! { a.invoke(p); } for a in o! { a.invoke(p) } } public func remove(_ action:Action<T>) { lock.synced { self.actions.remove(action) } } public func removeAll() { lock.synced { self.actions.removeAll() self.onces.removeAll() } } public init() { } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// #if os(macOS) || os(iOS) || os(tvOS) public class Lock { public func synced(_ execute: () -> ()) { objc_sync_enter(self) execute() objc_sync_exit(self) } public init() { } } #else public class Lock { let queue : DispatchQueue public func synced(_ execute: () -> ()) { queue.sync { execute() } } public init() { queue = DispatchQueue(label:Misc.alphaID) } } #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// #if os(macOS) || os(iOS) || os(tvOS) // TODO: use only DispatchSourceTimer class Timer : NSObject { var timer:Foundation.Timer? let tick:()->() init(period:Double,tick:@escaping ()->()) { self.tick=tick super.init() timer = Foundation.Timer.scheduledTimer(timeInterval: period, target: self, selector: #selector(update), userInfo: nil, repeats: true) } @objc func update() { tick() } func stop() { if let t=timer { t.invalidate() } timer=nil } } #else class Timer { var timer : DispatchSourceTimer? let tick:()->() init(period:Double,tick:@escaping ()->()) { self.tick=tick timer = DispatchSource.makeTimerSource() timer?.schedule(deadline:.now(),repeating:period,leeway:.milliseconds(100)) timer?.setEventHandler { [weak self] in self?.tick() } timer?.resume() } deinit { stop() } func stop() { timer?.cancel() timer = nil } } #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////
apache-2.0
72cb5065eb7c126cfff195d1df8465a8
33.58193
179
0.339784
5.631421
false
false
false
false
collinhundley/APTargets
UIControl+Target.swift
1
7688
// // UIControl+Target.swift // Created by Collin Hundley on 1/16/16 // // Useful code snippet for Xcode autocompletion: // addTarget(<#UIControlEvents#>) {[unowned self] in self.<#method#>} import UIKit public extension UIControl { /// The registry contains a weak reference to all UIControl objects that have been given targets, the events to observe, and the closures to execute when the events are triggered. private static var actionRegistry = [Action]() // MARK: Public methods /// Adds a target to the receiv er for the given event, which triggers the given action. public func addTarget(forControlEvents: UIControlEvents, action: () -> Void) { self.addTarget(forEvent: forControlEvents, action: action) } // MARK: Private methods /// A wrapper used to maintain a weak reference to a UIControl, an event to observe, and a function to call. private class Action: AnyObject { weak var object: UIControl? var event: UIControlEvents var function: Any init(object: UIControl, event: UIControlEvents, function: () -> Void) { self.object = object self.event = event self.function = function } init(object: UIControl, event: UIControlEvents, function: (sender: UIControl) -> Void) { self.object = object self.event = event self.function = function } } /// Adds the target to the actual object and adds the action to the registry. private func addTarget(forEvent event: UIControlEvents, action: () -> Void) { var actionString: Selector! switch event { // Touch events case UIControlEvents.TouchDown: actionString = "touchDown:" case UIControlEvents.TouchDownRepeat: actionString = "touchDownRepeat:" case UIControlEvents.TouchDragInside: actionString = "touchDragInside:" case UIControlEvents.TouchDragOutside: actionString = "touchDragOutside:" case UIControlEvents.TouchDragEnter: actionString = "touchDragEnter:" case UIControlEvents.TouchDragExit: actionString = "touchDragExit:" case UIControlEvents.TouchUpInside: actionString = "touchUpInside:" case UIControlEvents.TouchUpOutside: actionString = "touchUpOutside:" case UIControlEvents.TouchCancel: actionString = "touchCancel:" // UISlider events case UIControlEvents.ValueChanged: actionString = "valueChanged:" // tvOS button events case UIControlEvents.PrimaryActionTriggered: actionString = "primaryActionTriggered:" // UITextField events case UIControlEvents.EditingDidBegin: actionString = "editingDidBegin:" case UIControlEvents.EditingChanged: actionString = "editingChanged:" case UIControlEvents.EditingDidEnd: actionString = "editingDidEnd:" case UIControlEvents.EditingDidEndOnExit: actionString = "editingDidEndOnExit:" // Other events case UIControlEvents.AllTouchEvents: actionString = "allTouchEvents:" case UIControlEvents.AllEditingEvents: actionString = "allEditingEvents:" case UIControlEvents.ApplicationReserved: actionString = "applicationReserved:" case UIControlEvents.SystemReserved: actionString = "systemReserved:" case UIControlEvents.AllEvents: actionString = "allEvents:" default: // Unrecognized event break } // Add the Objective-C target self.addTarget(self, action: actionString, forControlEvents: event) // Register action UIControl.registerAction(Action(object: self, event: event, function: action)) } /// Adds an action to the registry. private static func registerAction(action: Action) { self.cleanRegistry() // Add action to the registry self.actionRegistry.append(action) } /// Triggers the actions for the correct control events. private func triggerAction(forObject: UIControl, event: UIControlEvents) { for action in UIControl.actionRegistry { if action.object == forObject && action.event == event { if let function = action.function as? () -> Void { function() } else if let function = action.function as? (sender: UIControl) -> Void { function(sender: forObject) } } } UIControl.cleanRegistry() } /// Cleans the registry, removing any actions whose object has already been released. /// This guarantees that no memory leaks will occur over time. private static func cleanRegistry() { UIControl.actionRegistry = UIControl.actionRegistry.filter({ $0.object != nil }) } // MARK: Targets given to the Objective-C selectors @objc private func touchDown(sender: UIControl) { triggerAction(sender, event: .TouchDown) } @objc private func touchDownRepeat(sender: UIControl) { triggerAction(sender, event: .TouchDownRepeat) } @objc private func touchDragInside(sender: UIControl) { triggerAction(sender, event: .TouchDragInside) } @objc private func touchDragOutside(sender: UIControl) { triggerAction(sender, event: .TouchDragOutside) } @objc private func touchDragEnter(sender: UIControl) { triggerAction(sender, event: .TouchDragEnter) } @objc private func touchDragExit(sender: UIControl) { triggerAction(sender, event: .TouchDragExit) } @objc private func touchUpInside(sender: UIControl) { triggerAction(sender, event: .TouchUpInside) } @objc private func touchUpOutside(sender: UIControl) { triggerAction(sender, event: .TouchUpOutside) } @objc private func touchCancel(sender: UIControl) { triggerAction(sender, event: .TouchCancel) } @objc private func valueChanged(sender: UIControl) { triggerAction(sender, event: .ValueChanged) } @objc private func primaryActionTriggered(sender: UIControl) { triggerAction(sender, event: .PrimaryActionTriggered) } @objc private func editingDidBegin(sender: UIControl) { triggerAction(sender, event: .EditingDidBegin) } @objc private func editingChanged(sender: UIControl) { triggerAction(sender, event: .EditingChanged) } @objc private func editingDidEnd(sender: UIControl) { triggerAction(sender, event: .EditingDidEnd) } @objc private func editingDidEndOnExit(sender: UIControl) { triggerAction(sender, event: .EditingDidEndOnExit) } @objc private func allTouchEvents(sender: UIControl) { triggerAction(sender, event: .AllTouchEvents) } @objc private func allEditingEvents(sender: UIControl) { triggerAction(sender, event: .AllEditingEvents) } @objc private func applicationReserved(sender: UIControl) { triggerAction(sender, event: .ApplicationReserved) } @objc private func systemReserved(sender: UIControl) { triggerAction(sender, event: .SystemReserved) } @objc private func allEvents(sender: UIControl) { triggerAction(sender, event: .AllEvents) } }
mit
1d241c1a05fe10a31ab2f1df1ef088e7
36.502439
183
0.637357
5.522989
false
false
false
false
ello/ello-ios
Sources/Controllers/Editorials/Cells/EditorialJoinCell.swift
1
6830
//// /// EditorialJoinCell.swift // class EditorialJoinCell: EditorialCellContent { private let joinLabel = StyledLabel(style: .editorialHeader) private let joinCaption = StyledLabel(style: .editorialCaption) private let emailField = ElloTextField() private let usernameField = ElloTextField() private let passwordField = ElloTextField() private let submitButton = StyledButton(style: .editorialJoin) var onJoinChange: ((Editorial.JoinInfo) -> Void)? private var isValid: Bool { guard let email = emailField.text, let username = usernameField.text, let password = passwordField.text else { return false } return Validator.hasValidSignUpCredentials( email: email, username: username, password: password, isTermsChecked: true ) } @objc func submitTapped() { guard let email = emailField.text, let username = usernameField.text, let password = passwordField.text else { return } let info: Editorial.JoinInfo = ( email: emailField.text, username: usernameField.text, password: passwordField.text, submitted: true ) onJoinChange?(info) emailField.isEnabled = false usernameField.isEnabled = false passwordField.isEnabled = false submitButton.isEnabled = false let responder: EditorialToolsResponder? = findResponder() responder?.submitJoin( cell: self.editorialCell, email: email, username: username, password: password ) } override func style() { super.style() joinLabel.text = InterfaceString.Editorials.Join joinLabel.isMultiline = true joinCaption.text = InterfaceString.Editorials.JoinCaption joinCaption.isMultiline = true ElloTextFieldView.styleAsEmailField(emailField) ElloTextFieldView.styleAsUsernameField(usernameField) ElloTextFieldView.styleAsPasswordField(passwordField) emailField.backgroundColor = .white emailField.placeholder = InterfaceString.Editorials.EmailPlaceholder usernameField.backgroundColor = .white usernameField.placeholder = InterfaceString.Editorials.UsernamePlaceholder passwordField.backgroundColor = .white passwordField.placeholder = InterfaceString.Editorials.PasswordPlaceholder submitButton.isEnabled = false submitButton.title = InterfaceString.Editorials.SubmitJoin } override func updateConfig() { super.updateConfig() emailField.text = config.join?.email usernameField.text = config.join?.username passwordField.text = config.join?.password let enabled = !(config.join?.submitted ?? false) emailField.isEnabled = enabled usernameField.isEnabled = enabled passwordField.isEnabled = enabled submitButton.isEnabled = enabled } override func bindActions() { super.bindActions() submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside) emailField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) usernameField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) passwordField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) } override func arrange() { super.arrange() editorialContentView.addSubview(joinLabel) editorialContentView.addSubview(joinCaption) editorialContentView.addSubview(emailField) editorialContentView.addSubview(usernameField) editorialContentView.addSubview(passwordField) editorialContentView.addSubview(submitButton) joinLabel.snp.makeConstraints { make in make.top.equalTo(editorialContentView).inset(Size.smallTopMargin) make.leading.equalTo(editorialContentView).inset(Size.defaultMargin) make.trailing.lessThanOrEqualTo(editorialContentView).inset(Size.defaultMargin) .priority(Priority.required) } joinCaption.snp.makeConstraints { make in make.top.equalTo(joinLabel.snp.bottom).offset(Size.textFieldMargin) make.leading.equalTo(editorialContentView).inset(Size.defaultMargin) make.trailing.lessThanOrEqualTo(editorialContentView).inset(Size.defaultMargin) .priority(Priority.required) } let fields = [emailField, usernameField, passwordField] fields.forEach { field in field.snp.makeConstraints { make in make.leading.trailing.equalTo(editorialContentView).inset(Size.defaultMargin) } } submitButton.snp.makeConstraints { make in make.height.equalTo(Size.buttonHeight).priority(Priority.required) make.bottom.equalTo(editorialContentView).offset(-Size.defaultMargin.bottom) make.leading.trailing.equalTo(editorialContentView).inset(Size.defaultMargin) } } override func layoutSubviews() { super.layoutSubviews() layoutIfNeeded() // why-t-f is this necessary!? // doing this simple height calculation in auto layout was a total waste of time let fields = [emailField, usernameField, passwordField] let textFieldsBottom = frame.height - Size.defaultMargin.bottom - Size.buttonHeight - Size.textFieldMargin var remainingHeight = textFieldsBottom - joinCaption.frame.maxY - Size.textFieldMargin - CGFloat(fields.count) * Size.joinMargin if remainingHeight < Size.minFieldHeight * 3 { joinCaption.isHidden = true remainingHeight += joinCaption.frame.height + Size.textFieldMargin } else { joinCaption.isVisible = true } let fieldHeight: CGFloat = min( max(ceil(remainingHeight / 3), Size.minFieldHeight), Size.maxFieldHeight ) var y: CGFloat = textFieldsBottom for field in fields.reversed() { y -= fieldHeight field.frame.origin.y = y field.frame.size.height = fieldHeight y -= Size.joinMargin } } override func prepareForReuse() { super.prepareForReuse() onJoinChange = nil } } extension EditorialJoinCell { @objc func textFieldDidChange() { let info: Editorial.JoinInfo = ( email: emailField.text, username: usernameField.text, password: passwordField.text, submitted: false ) onJoinChange?(info) submitButton.isEnabled = isValid } }
mit
d76b045c63b379ed4eeaa6063dff1e34
35.918919
98
0.659883
5.361068
false
false
false
false
austin226/maritime-flag-transliterator
Maritime Flag Transliterator/FlagCollectionViewController.swift
1
5246
// // FlagCollectionViewController.swift // Maritime Flag Transliterator // // Created by Austin Almond on 1/11/16. // Copyright © 2016 Austin Almond. All rights reserved. // import UIKit private let reuseIdentifier = "FlagCell" class FlagCollectionViewController: UICollectionViewController { var flagImages = [String]() var flagTextField: UITextField? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes //self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. flagImages = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliet", "kilo", "lima", "mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whiskey", "xray", "yankee", "zulu"] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return flagImages.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! FlagCollectionViewCell // Configure the cell let flagName = flagImages[indexPath.row] let image = UIImage(named: flagName) cell.imageView.image = image let initialChar = String(flagName[flagName.startIndex]).uppercaseString let tapGestureRecognizer = FlagTapGestureRecognizer(target: self, action: Selector("imageTapped:"), output: initialChar) cell.imageView.userInteractionEnabled = true cell.imageView.addGestureRecognizer(tapGestureRecognizer) return cell } func imageTapped(img: AnyObject) { if let flag_output = (img as! FlagTapGestureRecognizer).output { flagTextField!.text = flagTextField!.text?.stringByAppendingString(flag_output) } } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { var header: HeaderView? if kind == UICollectionElementKindSectionHeader { header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "ViewHeader", forIndexPath: indexPath) as? HeaderView header?.headerLabel.text = "Maritime Flag Transliterator" flagTextField = header?.flagTextField } return header! } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ }
gpl-3.0
85c387f6d2fe13f89527d3a43ea5d475
37.007246
185
0.676644
5.86689
false
false
false
false
wbaumann/SmartReceiptsiOS
SmartReceipts/Common/UI/Eureka Custom Cells/InputTextCell.swift
2
1391
// // InputTextCell.swift // SmartReceipts // // Created by Bogdan Evsenev on 07/07/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import Eureka public class InputTextCell: TextCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var valueField: UITextField! private var textFieldColor: UIColor! public override func setup() { textField = valueField titleLabel = label textFieldColor = valueField.backgroundColor super.setup() height = { 58 } } public override func update() { super.update() titleLabel?.text = row.title textField?.text = row.value textField.backgroundColor = textField.isUserInteractionEnabled ? textFieldColor : #colorLiteral(red: 0.9637350795, green: 0.9637350795, blue: 0.9637350795, alpha: 1) } private func row() -> InputTextRow { return (row as! InputTextRow) } } public final class InputTextRow: Row<InputTextCell>, RowType { required public init(tag: String?) { super.init(tag: tag) cellProvider = CellProvider<InputTextCell>(nibName: "InputTextCell") } var isEnabled: Bool { get { return cell.valueField.isUserInteractionEnabled } set { cell.valueField.isUserInteractionEnabled = newValue updateCell() } } }
agpl-3.0
89686bb9c0714439bfa32872eb8d2392
25.730769
173
0.639568
4.61794
false
false
false
false
Tronicnotes/FlatMum
FlatMum/GradientView.swift
1
931
// // GradientViewController.swift // FlatMum // // Created by Kurt Mohring on 29/04/17. // Copyright © 2017 Kurt Mohring. All rights reserved. // import UIKit @IBDesignable class GradientView: UIView { @IBInspectable var InsideColour: UIColor = UIColor.clear @IBInspectable var OutsideColour: UIColor = UIColor.clear override func draw(_ rect: CGRect) { let colours = [InsideColour.cgColor, OutsideColour.cgColor] as CFArray let endRadius = max(frame.width, frame.height) / 2 let center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2) let gradient = CGGradient(colorsSpace: nil, colors: colours, locations: nil) UIGraphicsGetCurrentContext()!.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: endRadius, options: CGGradientDrawingOptions.drawsAfterEndLocation) } }
gpl-3.0
3993c3918b20c2f71a27ea43522349c9
32.214286
205
0.692473
4.449761
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBAConsentSharingStep.swift
1
6010
// // SBAConsentSharingStep.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit public final class SBAConsentSharingStep: ORKConsentSharingStep, SBALearnMoreActionStep { public var learnMoreAction: SBALearnMoreAction? public override func stepViewControllerClass() -> AnyClass { return SBAConsentSharingStepViewController.classForCoder() } public init(inputItem: SBASurveyItem) { let share = inputItem as? SBAConsentSharingOptions let investigatorShortDescription = share?.investigatorShortDescription let investigatorLongDescription = share?.investigatorLongDescription // Use placeholder values if the investigator is nil for either the short or long // description. This is because the super class will assert if these values are nil super.init(identifier: inputItem.identifier, investigatorShortDescription: investigatorShortDescription ?? "PLACEHOLDER", investigatorLongDescription: investigatorLongDescription ?? "PLACEHOLDER", localizedLearnMoreHTMLContent: "PLACEHOLDER") if investigatorLongDescription == nil { // If there is no long description then use the text from the input item self.text = inputItem.stepText } else if let additionalText = inputItem.stepText, let text = self.text { // Otherwise, append the text built by the super class self.text = String.localizedStringWithFormat("%@\n\n%@", text, additionalText) } // If the inputItem has custom values for the choices, use those if let form = inputItem as? SBAFormStepSurveyItem, let textChoices = form.items?.map({form.createTextChoice(from: $0)}) { self.answerFormat = ORKTextChoiceAnswerFormat(style: .singleChoice, textChoices: textChoices) } // Finally, setup the learn more. The learn more html from the parent is ignored if let learnMoreURLString = share?.localizedLearnMoreHTMLContent { self.learnMoreAction = SBAURLLearnMoreAction(identifier: learnMoreURLString) } } // MARK: NSCopy public override init(identifier: String) { super.init(identifier: identifier) } override open func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) guard let step = copy as? SBAConsentSharingStep else { return copy } step.learnMoreAction = self.learnMoreAction return step } // MARK: NSCoding required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); self.learnMoreAction = aDecoder.decodeObject(forKey: #keyPath(learnMoreAction)) as? SBALearnMoreAction } override open func encode(with aCoder: NSCoder){ super.encode(with: aCoder) aCoder.encode(self.learnMoreAction, forKey: #keyPath(learnMoreAction)) } // MARK: Equality override open func isEqual(_ object: Any?) -> Bool { guard let object = object as? SBAInstructionStep else { return false } return super.isEqual(object) && SBAObjectEquality(self.learnMoreAction, object.learnMoreAction) } override open var hash: Int { return super.hash ^ SBAObjectHash(learnMoreAction) } } class SBAConsentSharingStepViewController: ORKQuestionStepViewController, SBASharedInfoController { lazy var sharedAppDelegate: SBAAppInfoDelegate = { return UIApplication.shared.delegate as! SBAAppInfoDelegate }() // Override the default method for goForward and attempt user registration. Do not allow subclasses // to override this method final override func goForward() { // Set the user's sharing scope sharedUser.dataSharingScope = { guard let choice = self.result?.results?.first as? ORKChoiceQuestionResult, let answer = choice.choiceAnswers?.first as? Bool else { return .none } return answer ? .all : .study }() // finally call through to super to continue once the consent sharing scope has been stored super.goForward() } }
bsd-3-clause
293136e3de3739de082eecdeac31be5a
41.617021
110
0.692295
5.418395
false
false
false
false
1457792186/JWSwift
SwiftLearn/SwiftDemo/Pods/MonkeyKing/Sources/MonkeyKing+WebView.swift
1
10356
import WebKit extension MonkeyKing: WKNavigationDelegate { public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Swift.Error) { // Pocket OAuth if let errorString = (error as NSError).userInfo["ErrorFailingURLStringKey"] as? String, errorString.hasSuffix(":authorizationFinished") { removeWebView(webView, tuples: (nil, nil, nil)) return } // Failed to connect network activityIndicatorViewAction(webView, stop: true) addCloseButton() let detailLabel = UILabel() detailLabel.text = "无法连接,请检查网络后重试" detailLabel.textColor = UIColor.gray detailLabel.translatesAutoresizingMaskIntoConstraints = false let centerX = NSLayoutConstraint(item: detailLabel, attribute: .centerX, relatedBy: .equal, toItem: webView, attribute: .centerX, multiplier: 1.0, constant: 0.0) let centerY = NSLayoutConstraint(item: detailLabel, attribute: .centerY, relatedBy: .equal, toItem: webView, attribute: .centerY, multiplier: 1.0, constant: -50.0) webView.addSubview(detailLabel) webView.addConstraints([centerX,centerY]) webView.scrollView.alwaysBounceVertical = false } public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { activityIndicatorViewAction(webView, stop: true) addCloseButton() guard let urlString = webView.url?.absoluteString else { return } var scriptString = "" if urlString.contains("getpocket.com") { scriptString += "document.querySelector('div.toolbar').style.display = 'none';" scriptString += "document.querySelector('a.extra_action').style.display = 'none';" scriptString += "var rightButton = $('.toolbarContents div:last-child');" scriptString += "if (rightButton.html() == 'Log In') {rightButton.click()}" } else if urlString.contains("api.weibo.com") { scriptString += "document.querySelector('aside.logins').style.display = 'none';" } webView.evaluateJavaScript(scriptString, completionHandler: nil) } public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { guard let url = webView.url else { webView.stopLoading() return } // twitter access token for case let .twitter(appID, appKey, redirectURL) in accountSet { guard url.absoluteString.hasPrefix(redirectURL) else { break } var parametersString = url.absoluteString for _ in (0...redirectURL.count) { parametersString.remove(at: parametersString.startIndex) } let params = parametersString.queryStringParameters guard let token = params["oauth_token"], let verifer = params["oauth_verifier"] else { break } let accessTokenAPI = "https://api.twitter.com/oauth/access_token" let parameters = ["oauth_token": token, "oauth_verifier": verifer] let headerString = Networking.shared.authorizationHeader(for: .post, urlString: accessTokenAPI, appID: appID, appKey: appKey, accessToken: nil, accessTokenSecret: nil, parameters: parameters, isMediaUpload: false) let oauthHeader = ["Authorization": headerString] request(accessTokenAPI, method: .post, parameters: nil, encoding: .url, headers: oauthHeader) { [weak self] (responseData, httpResponse, error) in DispatchQueue.main.async { [weak self] in self?.removeWebView(webView, tuples: (responseData, httpResponse, error)) } } return } // QQ Web OAuth guard url.absoluteString.contains("&access_token=") && url.absoluteString.contains("qq.com") else { return } guard let fragment = url.fragment?.dropFirst(), let newURL = URL(string: "https://qzs.qq.com/?\(String(fragment))") else { return } let queryDictionary = newURL.monkeyking_queryDictionary as [String: Any] removeWebView(webView, tuples: (queryDictionary, nil, nil)) } public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { guard let url = webView.url else { return } // WeChat OAuth if url.absoluteString.hasPrefix("wx") { let queryDictionary = url.monkeyking_queryDictionary guard let code = queryDictionary["code"] as? String else { return } MonkeyKing.fetchWeChatOAuthInfoByCode(code: code) { [weak self] (info, response, error) in self?.removeWebView(webView, tuples: (info, response, error)) } } else { // Weibo OAuth for case let .weibo(appID, appKey, redirectURL) in accountSet { if url.absoluteString.lowercased().hasPrefix(redirectURL) { webView.stopLoading() guard let code = url.monkeyking_queryDictionary["code"] as? String else { return } var accessTokenAPI = "https://api.weibo.com/oauth2/access_token?" accessTokenAPI += "client_id=" + appID accessTokenAPI += "&client_secret=" + appKey accessTokenAPI += "&grant_type=authorization_code" accessTokenAPI += "&redirect_uri=" + redirectURL accessTokenAPI += "&code=" + code activityIndicatorViewAction(webView, stop: false) request(accessTokenAPI, method: .post) { [weak self] (json, response, error) in DispatchQueue.main.async { [weak self] in self?.removeWebView(webView, tuples: (json, response, error)) } } } } } } } extension MonkeyKing { class func generateWebView() -> WKWebView { let webView = WKWebView() let screenBounds = UIScreen.main.bounds webView.frame = CGRect(origin: CGPoint(x: 0, y: screenBounds.height), size: CGSize(width: screenBounds.width, height: screenBounds.height - 20)) webView.navigationDelegate = shared webView.backgroundColor = UIColor(red: 247/255, green: 247/255, blue: 247/255, alpha: 1.0) webView.scrollView.backgroundColor = webView.backgroundColor UIApplication.shared.keyWindow?.addSubview(webView) return webView } class func addWebView(withURLString urlString: String) { if nil == MonkeyKing.shared.webView { MonkeyKing.shared.webView = generateWebView() } guard let url = URL(string: urlString), let webView = MonkeyKing.shared.webView else { return } webView.load(URLRequest(url: url)) let activityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 0.0, y: 0.0, width: 20.0, height: 20.0)) activityIndicatorView.center = CGPoint(x: webView.bounds.midX, y: webView.bounds.midY + 30.0) activityIndicatorView.activityIndicatorViewStyle = .gray webView.scrollView.addSubview(activityIndicatorView) activityIndicatorView.startAnimating() UIView.animate(withDuration: 0.32, delay: 0.0, options: .curveEaseOut, animations: { webView.frame.origin.y = 20.0 }, completion: nil) } func addCloseButton() { guard let webView = webView else { return } let closeButton = CloseButton(type: .custom) closeButton.frame = CGRect(origin: CGPoint(x: UIScreen.main.bounds.width - 50.0, y: 4.0), size: CGSize(width: 44.0, height: 44.0)) closeButton.addTarget(self, action: #selector(closeOauthView), for: .touchUpInside) webView.addSubview(closeButton) } @objc func closeOauthView() { guard let webView = webView else { return } let error = NSError(domain: "User Cancelled", code: -1, userInfo: nil) removeWebView(webView, tuples: (nil, nil, error)) } func removeWebView(_ webView: WKWebView, tuples: ([String: Any]?, URLResponse?, Swift.Error?)?) { activityIndicatorViewAction(webView, stop: true) webView.stopLoading() UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseOut, animations: { webView.frame.origin.y = UIScreen.main.bounds.height }, completion: { [weak self] _ in webView.removeFromSuperview() MonkeyKing.shared.webView = nil self?.oauthCompletionHandler?(tuples?.0, tuples?.1, tuples?.2) }) } func activityIndicatorViewAction(_ webView: WKWebView, stop: Bool) { for subview in webView.scrollView.subviews { if let activityIndicatorView = subview as? UIActivityIndicatorView { guard stop else { activityIndicatorView.startAnimating() return } activityIndicatorView.stopAnimating() } } } } class CloseButton: UIButton { override func draw(_ rect: CGRect) { let circleWidth: CGFloat = 28.0 let circlePathX = (rect.width - circleWidth) / 2.0 let circlePathY = (rect.height - circleWidth) / 2.0 let circlePathRect = CGRect(x: circlePathX, y: circlePathY, width: circleWidth, height: circleWidth) let circlePath = UIBezierPath(ovalIn: circlePathRect) UIColor(white: 0.8, alpha: 1.0).setFill() circlePath.fill() let xPath = UIBezierPath() xPath.lineCapStyle = .round xPath.lineWidth = 3.0 let offset: CGFloat = (bounds.width - circleWidth) / 2.0 xPath.move(to: CGPoint(x: offset + circleWidth / 3.0, y: offset + circleWidth / 3.0)) xPath.addLine(to: CGPoint(x: offset + 2.0 * circleWidth / 3.0, y: offset + 2.0 * circleWidth / 3.0)) xPath.move(to: CGPoint(x: offset + circleWidth / 3.0, y: offset + 2.0 * circleWidth / 3.0)) xPath.addLine(to: CGPoint(x: offset + 2.0 * circleWidth / 3.0, y: offset + circleWidth / 3.0)) UIColor.white.setStroke() xPath.stroke() } }
apache-2.0
211994aef5b7dfda97d386049bd7cfc8
49.8867
225
0.624298
4.815851
false
false
false
false
limsangjin12/Hero
Examples/ExampleViewController.swift
1
2191
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Hero class ExampleViewController: UITableViewController { var storyboards: [[String]] = [ [], ["Basic", "MusicPlayer", "Menu", "BuiltInTransitions"], ["CityGuide", "ImageViewer", "VideoPlayer"], ["AppleHomePage", "ListToGrid", "ImageGallery"] ] override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottomLayoutGuide.length, right: 0) tableView.scrollIndicatorInsets = tableView.contentInset } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.item < storyboards[indexPath.section].count { let storyboardName = storyboards[indexPath.section][indexPath.item] let vc = viewController(forStoryboardName: storyboardName) // iOS bug: https://github.com/lkzhao/Hero/issues/106 https://github.com/lkzhao/Hero/issues/79 DispatchQueue.main.async { self.present(vc, animated: true, completion: nil) } } } }
mit
151684544c6cc11d1effce00c406463e
41.134615
102
0.735737
4.564583
false
false
false
false
quickthyme/PUTcat
PUTcat/Presentation/TransactionDetail/TableViewCell/TransactionDetailValueCell.swift
1
2890
import UIKit class TransactionDetailValueCell: UITableViewCell { @IBOutlet weak var overrideTextLabel : UILabel? @IBOutlet weak var overrideDetailTextLabel : UILabel? override var textLabel: UILabel? { return self.overrideTextLabel } override var detailTextLabel: UILabel? { return self.overrideDetailTextLabel } var detailTextColor : UIColor = AppColor.Text.Light var isTextEditingAllowed : Bool = false var detailTextChanged : ((String) -> ())? lazy var detailTextField : UITextField = { let field = UITextField(frame: self.detailTextLabel?.bounds ?? CGRect.zero) field.borderStyle = .none field.textAlignment = .right field.textColor = self.detailTextColor field.autocapitalizationType = .none field.autocorrectionType = .no field.delegate = self return field }() } extension TransactionDetailValueCell : TransactionDetailViewDataItemConfigurable, TransactionDetailViewDataItemEditable { func configure(transactionDetailViewDataItem item: TransactionDetailViewDataItem) { self.textLabel?.text = item.title self.detailTextLabel?.text = item.detail let detailColor = item.detailColor ?? AppColor.Text.Light self.detailTextColor = detailColor self.detailTextLabel?.textColor = detailColor self.accessoryType = item.accessory let isEditable = (item.detailEditKey != nil) self.isTextEditingAllowed = isEditable self.selectionStyle = (isEditable) ? .none : .default if (isEditable) { self.detailTextField.text = item.detail self.detailTextField.textColor = detailColor self.detailTextField.placeholder = item.detail } } func showDetailTextField() { guard isTextEditingAllowed else { return } if let label = self.detailTextLabel { detailTextField.frame = label.bounds label.textColor = UIColor.clear label.addSubview(detailTextField) detailTextField.becomeFirstResponder() } } func hideDetailTextField() { guard isTextEditingAllowed else { return } if let label = self.detailTextLabel { detailTextField.resignFirstResponder() label.textColor = self.detailTextColor detailTextField.removeFromSuperview() } } } extension TransactionDetailValueCell : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField) { guard isTextEditingAllowed else { return } if (textField === self.detailTextField) { self.detailTextLabel?.text = textField.text self.detailTextChanged?(textField.text ?? "") } } }
apache-2.0
083e857638571199f13c8528821a5fd7
33
121
0.676817
5.622568
false
false
false
false
natsu1211/Alarm-ios-swift
IOS/Alarm/AlarmModel.swift
1
3096
// // AlarmModel.swift // Alarm-ios-swift // // Created by longyutao on 15-2-28. // Updated on 17-01-24 // Copyright (c) 2015年 LongGames. All rights reserved. // import Foundation import MediaPlayer struct Alarm: PropertyReflectable { var date: Date = Date() var enabled: Bool = false var snoozeEnabled: Bool = false var repeatWeekdays: [Int] = [] var uuid: String = "" var mediaID: String = "" var mediaLabel: String = "bell" var label: String = "Alarm" var onSnooze: Bool = false init(){} init(date:Date, enabled:Bool, snoozeEnabled:Bool, repeatWeekdays:[Int], uuid:String, mediaID:String, mediaLabel:String, label:String, onSnooze: Bool){ self.date = date self.enabled = enabled self.snoozeEnabled = snoozeEnabled self.repeatWeekdays = repeatWeekdays self.uuid = uuid self.mediaID = mediaID self.mediaLabel = mediaLabel self.label = label self.onSnooze = onSnooze } init(_ dict: PropertyReflectable.RepresentationType){ date = dict["date"] as! Date enabled = dict["enabled"] as! Bool snoozeEnabled = dict["snoozeEnabled"] as! Bool repeatWeekdays = dict["repeatWeekdays"] as! [Int] uuid = dict["uuid"] as! String mediaID = dict["mediaID"] as! String mediaLabel = dict["mediaLabel"] as! String label = dict["label"] as! String onSnooze = dict["onSnooze"] as! Bool } static var propertyCount: Int = 9 } extension Alarm { var formattedTime: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "h:mm a" return dateFormatter.string(from: self.date) } } //This can be considered as a viewModel class Alarms: Persistable { let ud: UserDefaults = UserDefaults.standard let persistKey: String = "myAlarmKey" var alarms: [Alarm] = [] { //observer, sync with UserDefaults didSet{ persist() } } private func getAlarmsDictRepresentation()->[PropertyReflectable.RepresentationType] { return alarms.map {$0.propertyDictRepresentation} } init() { alarms = getAlarms() } func persist() { ud.set(getAlarmsDictRepresentation(), forKey: persistKey) ud.synchronize() } func unpersist() { for key in ud.dictionaryRepresentation().keys { UserDefaults.standard.removeObject(forKey: key.description) } } var count: Int { return alarms.count } //helper, get all alarms from Userdefaults private func getAlarms() -> [Alarm] { let array = UserDefaults.standard.array(forKey: persistKey) guard let alarmArray = array else{ return [Alarm]() } if let dicts = alarmArray as? [PropertyReflectable.RepresentationType]{ if dicts.first?.count == Alarm.propertyCount { return dicts.map{Alarm($0)} } } unpersist() return [Alarm]() } }
mit
1417c4752aef5012b4fab8b5507405cf
27.385321
154
0.607304
4.451799
false
false
false
false
Suninus/Stick-Hero-Swift
Stick-Hero/StickHeroGameScene.swift
6
21369
// // StickHeroGameScene.swift // Stick-Hero // // Created by 顾枫 on 15/6/19. // Copyright © 2015年 koofrank. All rights reserved. // import SpriteKit class StickHeroGameScene: SKScene, SKPhysicsContactDelegate { var gameOver = false { willSet { if (newValue) { checkHighScoreAndStore() let gameOverLayer = childNodeWithName(StickHeroGameSceneChildName.GameOverLayerName.rawValue) as SKNode? gameOverLayer?.runAction(SKAction.moveDistance(CGVectorMake(0, 100), fadeInWithDuration: 0.2)) } } } let StackHeight:CGFloat = 400.0 let StackMaxWidth:CGFloat = 300.0 let StackMinWidth:CGFloat = 100.0 let gravity:CGFloat = -100.0 let StackGapMinWidth:Int = 80 let HeroSpeed:CGFloat = 760 let StoreScoreName = "com.stickHero.score" var isBegin = false var isEnd = false var leftStack:SKShapeNode? var rightStack:SKShapeNode? var nextLeftStartX:CGFloat = 0 var stickHeight:CGFloat = 0 var score:Int = 0 { willSet { let scoreBand = childNodeWithName(StickHeroGameSceneChildName.ScoreName.rawValue) as? SKLabelNode scoreBand?.text = "\(newValue)" scoreBand?.runAction(SKAction.sequence([SKAction.scaleTo(1.5, duration: 0.1), SKAction.scaleTo(1, duration: 0.1)])) if (newValue == 1) { let tip = childNodeWithName(StickHeroGameSceneChildName.TipName.rawValue) as? SKLabelNode tip?.runAction(SKAction.fadeAlphaTo(0, duration: 0.4)) } } } lazy var playAbleRect:CGRect = { let maxAspectRatio:CGFloat = 16.0/9.0 // iPhone 5" let maxAspectRatioWidth = self.size.height / maxAspectRatio let playableMargin = (self.size.width - maxAspectRatioWidth) / 2.0 return CGRectMake(playableMargin, 0, maxAspectRatioWidth, self.size.height) }() lazy var walkAction:SKAction = { var textures:[SKTexture] = [] for i in 0...1 { let texture = SKTexture(imageNamed: "human\(i + 1).png") textures.append(texture) } let action = SKAction.animateWithTextures(textures, timePerFrame: 0.15, resize: true, restore: true) return SKAction.repeatActionForever(action) }() //MARK: - override override init(size: CGSize) { super.init(size: size) anchorPoint = CGPointMake(0.5, 0.5) physicsWorld.contactDelegate = self } override func didMoveToView(view: SKView) { start() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { guard !gameOver else { let gameOverLayer = childNodeWithName(StickHeroGameSceneChildName.GameOverLayerName.rawValue) as SKNode? let location = touches.first?.locationInNode(gameOverLayer!) let retry = gameOverLayer!.nodeAtPoint(location!) if (retry.name == StickHeroGameSceneChildName.RetryButtonName.rawValue) { retry.runAction(SKAction.sequence([SKAction.setTexture(SKTexture(imageNamed: "button_retry_down"), resize: false), SKAction.waitForDuration(0.3)]), completion: {[unowned self] () -> Void in self.restart() }) } return } if !isBegin && !isEnd { isBegin = true let stick = loadStick() let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode let action = SKAction.resizeToHeight(CGFloat(DefinedScreenHeight - StackHeight), duration: 1.5) stick.runAction(action, withKey:StickHeroGameSceneActionKey.StickGrowAction.rawValue) let scaleAction = SKAction.sequence([SKAction.scaleYTo(0.9, duration: 0.05), SKAction.scaleYTo(1, duration: 0.05)]) let loopAction = SKAction.group([SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickGrowAudioName.rawValue, waitForCompletion: true)]) stick.runAction(SKAction.repeatActionForever(loopAction), withKey: StickHeroGameSceneActionKey.StickGrowAudioAction.rawValue) hero.runAction(SKAction.repeatActionForever(scaleAction), withKey: StickHeroGameSceneActionKey.HeroScaleAction.rawValue) return } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if isBegin && !isEnd { isEnd = true let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode hero.removeActionForKey(StickHeroGameSceneActionKey.HeroScaleAction.rawValue) hero.runAction(SKAction.scaleYTo(1, duration: 0.04)) let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode stick.removeActionForKey(StickHeroGameSceneActionKey.StickGrowAction.rawValue) stick.removeActionForKey(StickHeroGameSceneActionKey.StickGrowAudioAction.rawValue) stick.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickGrowOverAudioName.rawValue, waitForCompletion: false)) stickHeight = stick.size.height; let action = SKAction.rotateToAngle(CGFloat(-M_PI / 2), duration: 0.4, shortestUnitArc: true) let playFall = SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickFallAudioName.rawValue, waitForCompletion: false) stick.runAction(SKAction.sequence([SKAction.waitForDuration(0.2), action, playFall]), completion: {[unowned self] () -> Void in self.heroGo(self.checkPass()) }) } } func start() { loadBackground() loadScoreBackground() loadScore() loadTip() loadGameOverLayer() leftStack = loadStacks(false, startLeftPoint: playAbleRect.origin.x) self.removeMidTouch(false, left:true) loadHero() let maxGap = Int(playAbleRect.width - StackMaxWidth - (leftStack?.frame.size.width)!) let gap = CGFloat(randomInRange(StackGapMinWidth...maxGap)) rightStack = loadStacks(false, startLeftPoint: nextLeftStartX + gap) gameOver = false } func restart() { //记录分数 isBegin = false isEnd = false score = 0 nextLeftStartX = 0 removeAllChildren() start() } private func checkPass() -> Bool { let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode let rightPoint = DefinedScreenWidth / 2 + stick.position.x + self.stickHeight guard rightPoint < self.nextLeftStartX else { return false } guard (CGRectIntersectsRect((leftStack?.frame)!, stick.frame) && CGRectIntersectsRect((rightStack?.frame)!, stick.frame)) else { return false } self.checkTouchMidStack() return true } private func checkTouchMidStack() { let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode let stackMid = rightStack!.childNodeWithName(StickHeroGameSceneChildName.StackMidName.rawValue) as! SKShapeNode let newPoint = stackMid.convertPoint(CGPointMake(-10, 10), toNode: self) if ((stick.position.x + self.stickHeight) >= newPoint.x && (stick.position.x + self.stickHeight) <= newPoint.x + 20) { loadPerfect() self.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.StickTouchMidAudioName.rawValue, waitForCompletion: false)) score++ } } private func removeMidTouch(animate:Bool, left:Bool) { let stack = left ? leftStack : rightStack let mid = stack!.childNodeWithName(StickHeroGameSceneChildName.StackMidName.rawValue) as! SKShapeNode if (animate) { mid.runAction(SKAction.fadeAlphaTo(0, duration: 0.3)) } else { mid.removeFromParent() } } private func heroGo(pass:Bool) { let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode guard pass else { let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode let dis:CGFloat = stick.position.x + self.stickHeight let disGap = nextLeftStartX - (DefinedScreenWidth / 2 - abs(hero.position.x)) - (rightStack?.frame.size.width)! / 2 let move = SKAction.moveToX(dis, duration: NSTimeInterval(abs(disGap / HeroSpeed))) hero.runAction(walkAction, withKey: StickHeroGameSceneActionKey.WalkAction.rawValue) hero.runAction(move, completion: {[unowned self] () -> Void in stick.runAction(SKAction.rotateToAngle(CGFloat(-M_PI), duration: 0.4)) hero.physicsBody!.affectedByGravity = true hero.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.DeadAudioName.rawValue, waitForCompletion: false)) hero.removeActionForKey(StickHeroGameSceneActionKey.WalkAction.rawValue) self.runAction(SKAction.waitForDuration(0.5), completion: {[unowned self] () -> Void in self.gameOver = true }) }) return } let dis:CGFloat = -DefinedScreenWidth / 2 + nextLeftStartX - hero.size.width / 2 - 20 let disGap = nextLeftStartX - (DefinedScreenWidth / 2 - abs(hero.position.x)) - (rightStack?.frame.size.width)! / 2 let move = SKAction.moveToX(dis, duration: NSTimeInterval(abs(disGap / HeroSpeed))) hero.runAction(walkAction, withKey: StickHeroGameSceneActionKey.WalkAction.rawValue) hero.runAction(move) { [unowned self]() -> Void in self.score++ hero.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.VictoryAudioName.rawValue, waitForCompletion: false)) hero.removeActionForKey(StickHeroGameSceneActionKey.WalkAction.rawValue) self.moveStackAndCreateNew() } } private func checkHighScoreAndStore() { let highScore = NSUserDefaults.standardUserDefaults().integerForKey(StoreScoreName) if (score > Int(highScore)) { showHighScore() NSUserDefaults.standardUserDefaults().setInteger(score, forKey: StoreScoreName) NSUserDefaults.standardUserDefaults().synchronize() } } private func showHighScore() { self.runAction(SKAction.playSoundFileNamed(StickHeroGameSceneEffectAudioName.HighScoreAudioName.rawValue, waitForCompletion: false)) let wait = SKAction.waitForDuration(0.4) let grow = SKAction.scaleTo(1.5, duration: 0.4) grow.timingMode = .EaseInEaseOut let explosion = starEmitterActionAtPosition(CGPointMake(0, 300)) let shrink = SKAction.scaleTo(1, duration: 0.2) let idleGrow = SKAction.scaleTo(1.2, duration: 0.4) idleGrow.timingMode = .EaseInEaseOut let idleShrink = SKAction.scaleTo(1, duration: 0.4) let pulsate = SKAction.repeatActionForever(SKAction.sequence([idleGrow, idleShrink])) let gameOverLayer = childNodeWithName(StickHeroGameSceneChildName.GameOverLayerName.rawValue) as SKNode? let highScoreLabel = gameOverLayer?.childNodeWithName(StickHeroGameSceneChildName.HighScoreName.rawValue) as SKNode? highScoreLabel?.runAction(SKAction.sequence([wait, explosion, grow, shrink]), completion: { () -> Void in highScoreLabel?.runAction(pulsate) }) } private func moveStackAndCreateNew() { let action = SKAction.moveBy(CGVectorMake(-nextLeftStartX + (rightStack?.frame.size.width)! + playAbleRect.origin.x - 2, 0), duration: 0.3) rightStack?.runAction(action) self.removeMidTouch(true, left:false) let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode let stick = childNodeWithName(StickHeroGameSceneChildName.StickName.rawValue) as! SKSpriteNode hero.runAction(action) stick.runAction(SKAction.group([SKAction.moveBy(CGVectorMake(-DefinedScreenWidth, 0), duration: 0.5), SKAction.fadeAlphaTo(0, duration: 0.3)])) { () -> Void in stick.removeFromParent() } leftStack?.runAction(SKAction.moveBy(CGVectorMake(-DefinedScreenWidth, 0), duration: 0.5), completion: {[unowned self] () -> Void in self.leftStack?.removeFromParent() let maxGap = Int(self.playAbleRect.width - (self.rightStack?.frame.size.width)! - self.StackMaxWidth) let gap = CGFloat(randomInRange(self.StackGapMinWidth...maxGap)) self.leftStack = self.rightStack self.rightStack = self.loadStacks(true, startLeftPoint:self.playAbleRect.origin.x + (self.rightStack?.frame.size.width)! + gap) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: - load node private extension StickHeroGameScene { func loadBackground() { guard let _ = childNodeWithName("background") as! SKSpriteNode? else { let texture = SKTexture(image: UIImage(named: "stick_background.jpg")!) let node = SKSpriteNode(texture: texture) node.size = texture.size() node.zPosition = StickHeroGameSceneZposition.BackgroundZposition.rawValue self.physicsWorld.gravity = CGVectorMake(0, gravity) addChild(node) return } } func loadScore() { let scoreBand = SKLabelNode(fontNamed: "Arial") scoreBand.name = StickHeroGameSceneChildName.ScoreName.rawValue scoreBand.text = "0" scoreBand.position = CGPointMake(0, DefinedScreenHeight / 2 - 200) scoreBand.fontColor = SKColor.whiteColor() scoreBand.fontSize = 100 scoreBand.zPosition = StickHeroGameSceneZposition.ScoreZposition.rawValue scoreBand.horizontalAlignmentMode = .Center addChild(scoreBand) } func loadScoreBackground() { let back = SKShapeNode(rect: CGRectMake(0-120, 1024-200-30, 240, 140), cornerRadius: 20) back.zPosition = StickHeroGameSceneZposition.ScoreBackgroundZposition.rawValue back.fillColor = SKColor.blackColor().colorWithAlphaComponent(0.3) back.strokeColor = SKColor.blackColor().colorWithAlphaComponent(0.3) addChild(back) } func loadHero() { let hero = SKSpriteNode(imageNamed: "human1") hero.name = StickHeroGameSceneChildName.HeroName.rawValue hero.position = CGPointMake(-DefinedScreenWidth / 2 + nextLeftStartX - hero.size.width / 2 - 20, -DefinedScreenHeight / 2 + StackHeight + hero.size.height / 2 - 4) hero.zPosition = StickHeroGameSceneZposition.HeroZposition.rawValue hero.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(16, 18)) hero.physicsBody?.affectedByGravity = false hero.physicsBody?.allowsRotation = false addChild(hero) } func loadTip() { let tip = SKLabelNode(fontNamed: "HelveticaNeue-Bold") tip.name = StickHeroGameSceneChildName.TipName.rawValue tip.text = "将手放在屏幕使竿变长" tip.position = CGPointMake(0, DefinedScreenHeight / 2 - 350) tip.fontColor = SKColor.blackColor() tip.fontSize = 52 tip.zPosition = StickHeroGameSceneZposition.TipZposition.rawValue tip.horizontalAlignmentMode = .Center addChild(tip) } func loadPerfect() { defer { let perfect = childNodeWithName(StickHeroGameSceneChildName.PerfectName.rawValue) as! SKLabelNode? let sequence = SKAction.sequence([SKAction.fadeAlphaTo(1, duration: 0.3), SKAction.fadeAlphaTo(0, duration: 0.3)]) let scale = SKAction.sequence([SKAction.scaleTo(1.4, duration: 0.3), SKAction.scaleTo(1, duration: 0.3)]) perfect!.runAction(SKAction.group([sequence, scale])) } guard let _ = childNodeWithName(StickHeroGameSceneChildName.PerfectName.rawValue) as! SKLabelNode? else { let perfect = SKLabelNode(fontNamed: "Arial") perfect.text = "Perfect +1" perfect.name = StickHeroGameSceneChildName.PerfectName.rawValue perfect.position = CGPointMake(0, -100) perfect.fontColor = SKColor.blackColor() perfect.fontSize = 50 perfect.zPosition = StickHeroGameSceneZposition.PerfectZposition.rawValue perfect.horizontalAlignmentMode = .Center perfect.alpha = 0 addChild(perfect) return } } func loadStick() -> SKSpriteNode { let hero = childNodeWithName(StickHeroGameSceneChildName.HeroName.rawValue) as! SKSpriteNode let stick = SKSpriteNode(color: SKColor.blackColor(), size: CGSizeMake(12, 1)) stick.zPosition = StickHeroGameSceneZposition.StickZposition.rawValue stick.name = StickHeroGameSceneChildName.StickName.rawValue stick.anchorPoint = CGPointMake(0.5, 0); stick.position = CGPointMake(hero.position.x + hero.size.width / 2 + 18, hero.position.y - hero.size.height / 2) addChild(stick) return stick } func loadStacks(animate: Bool, startLeftPoint: CGFloat) -> SKShapeNode { let max:Int = Int(StackMaxWidth / 10) let min:Int = Int(StackMinWidth / 10) let width:CGFloat = CGFloat(randomInRange(min...max) * 10) let height:CGFloat = StackHeight let stack = SKShapeNode(rectOfSize: CGSizeMake(width, height)) stack.fillColor = SKColor.blackColor() stack.strokeColor = SKColor.blackColor() stack.zPosition = StickHeroGameSceneZposition.StackZposition.rawValue stack.name = StickHeroGameSceneChildName.StackName.rawValue if (animate) { stack.position = CGPointMake(DefinedScreenWidth / 2, -DefinedScreenHeight / 2 + height / 2) stack.runAction(SKAction.moveToX(-DefinedScreenWidth / 2 + width / 2 + startLeftPoint, duration: 0.3), completion: {[unowned self] () -> Void in self.isBegin = false self.isEnd = false }) } else { stack.position = CGPointMake(-DefinedScreenWidth / 2 + width / 2 + startLeftPoint, -DefinedScreenHeight / 2 + height / 2) } addChild(stack) let mid = SKShapeNode(rectOfSize: CGSizeMake(20, 20)) mid.fillColor = SKColor.redColor() mid.strokeColor = SKColor.redColor() mid.zPosition = StickHeroGameSceneZposition.StackMidZposition.rawValue mid.name = StickHeroGameSceneChildName.StackMidName.rawValue mid.position = CGPointMake(0, height / 2 - 20 / 2) stack.addChild(mid) nextLeftStartX = width + startLeftPoint return stack } func loadGameOverLayer() { let node = SKNode() node.alpha = 0 node.name = StickHeroGameSceneChildName.GameOverLayerName.rawValue node.zPosition = StickHeroGameSceneZposition.GameOverZposition.rawValue addChild(node) let label = SKLabelNode(fontNamed: "HelveticaNeue-Bold") label.text = "Game Over" label.fontColor = SKColor.redColor() label.fontSize = 150 label.position = CGPointMake(0, 100) label.horizontalAlignmentMode = .Center node.addChild(label) let retry = SKSpriteNode(imageNamed: "button_retry_up") retry.name = StickHeroGameSceneChildName.RetryButtonName.rawValue retry.position = CGPointMake(0, -200) node.addChild(retry) let highScore = SKLabelNode(fontNamed: "AmericanTypewriter") highScore.text = "Highscore!" highScore.fontColor = UIColor.whiteColor() highScore.fontSize = 50 highScore.name = StickHeroGameSceneChildName.HighScoreName.rawValue highScore.position = CGPointMake(0, 300) highScore.horizontalAlignmentMode = .Center highScore.setScale(0) node.addChild(highScore) } //MARK: - Action func starEmitterActionAtPosition(position: CGPoint) -> SKAction { let emitter = SKEmitterNode(fileNamed: "StarExplosion") emitter?.position = position emitter?.zPosition = StickHeroGameSceneZposition.EmitterZposition.rawValue emitter?.alpha = 0.6 addChild((emitter)!) let wait = SKAction.waitForDuration(0.15) return SKAction.runBlock({ () -> Void in emitter?.runAction(wait) }) } }
mit
1adc77275f6a5b47b923cf85ae6cd50a
41.839357
205
0.646245
5.258565
false
false
false
false
tinrobots/Mechanica
Tests/FoundationTests/NSMutableAttributedStringUtilsTests.swift
1
15453
import XCTest @testable import Mechanica extension NSMutableAttributedStringUtilsTests { static var allTests = [ ("testRemovingAttributes", testRemovingAttributes), ("testRemoveAttributes", testRemoveAttributes), ("testAddition", testAddition), ("testCompoundAddition", testCompoundAddition), ] } final class NSMutableAttributedStringUtilsTests: XCTestCase { #if os(Linux) // NSAttributedStringKey // https://github.com/apple/swift-corelibs-foundation/blob/a61b058ed53b00621e7acba4c53959e3ae01a254/Foundation/NSAttributedString.swift let attributes1 = [NSAttributedStringKey("key1"): "A"] let attributes2 = [NSAttributedStringKey("key2"): "B"] let attributes3 = [NSAttributedStringKey("key1"): "A", NSAttributedStringKey("key3"): "C"] #else let attributes1 = [NSAttributedString.Key.foregroundColor: Color.red] let attributes2 = [NSAttributedString.Key.backgroundColor: Color.yellow] let attributes3 = [NSAttributedString.Key.foregroundColor: Color.red, NSAttributedString.Key.strikethroughColor: Color.blue] #endif func testRemovingAttributes() { do { // Given let attributedString = NSMutableAttributedString(string: "Hello", attributes: attributes1) attributedString += " " attributedString += NSMutableAttributedString(string: "Hello", attributes: attributes2) let range = NSRange(location: 0, length: attributedString.length) var attributesCount = 0 var attributesCount2 = 0 attributedString.enumerateAttributes(in: range, options: []) { (attributes, _, _) in if !attributes.keys.isEmpty { attributesCount += 1 } } // When let notAttributedString = attributedString.removingAllAttributes() let range2 = NSRange(location: 0, length: notAttributedString.length) // Then notAttributedString.enumerateAttributes(in: range2, options: []) { (attributes, _, _) in if !attributes.keys.isEmpty { attributesCount2 += 1 } } XCTAssertTrue(attributesCount != attributesCount2) XCTAssertTrue(attributesCount2 == 0) } do { let attributedString = NSMutableAttributedString(string: "Hello", attributes: attributes3) let range = NSRange(location: 0, length: attributedString.length) var attributesCount = 0 var attributesCount2 = 0 attributedString.enumerateAttributes(in: range, options: []) { (attributes, _, _) in if !attributes.keys.isEmpty { attributesCount += 1 } } // When let notAttributedString = attributedString.removingAllAttributes() let range2 = NSRange(location: 0, length: notAttributedString.length) // Then notAttributedString.enumerateAttributes(in: range2, options: []) { (attributes, _, _) in if !attributes.keys.isEmpty { attributesCount2 += 1 } } XCTAssertTrue(attributesCount != attributesCount2) XCTAssertTrue(attributesCount2 == 0) } } func testRemoveAttributes() { // Given let attributedString = NSMutableAttributedString(string: "Hello", attributes: attributes1) attributedString += " " attributedString += NSAttributedString(string: "World", attributes: attributes2) let range = NSRange(location: 0, length: attributedString.length) var attributesCount = 0 var attributesCount2 = 0 attributedString.enumerateAttributes(in: range, options: []) { (attributes, _, _) in if !attributes.keys.isEmpty { attributesCount += 1 } } // When attributedString.removeAllAttributes() let range2 = NSRange(location: 0, length: attributedString.length) // Then attributedString.enumerateAttributes(in: range2, options: []) { (attributes, _, _) in if !attributes.keys.isEmpty { attributesCount2 += 1 } } XCTAssertTrue(attributesCount != attributesCount2) XCTAssertTrue(attributesCount2 == 0) } func testAddition() { /// addition between NSMutableAttributedStrings do { let s1 = NSMutableAttributedString(string: "Hello") let s2 = NSMutableAttributedString(string: " ") let s3 = NSMutableAttributedString(string: "World") let s4 = s1 + s2 + s3 XCTAssertTrue(s4.string == "Hello World") } do { #if !os(Linux) let s1 = NSMutableAttributedString(string: "Hello", attributes: [NSAttributedString.Key.foregroundColor: Color.red]) let s2 = NSMutableAttributedString(string: " ") let s3 = NSMutableAttributedString(string: "World", attributes: [NSAttributedString.Key.backgroundColor: Color.yellow]) let s4 = s1 + s2 + s3 let firstCharAttributes = s4.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, 0)) let lastCharAttributes = s4.attributes(at: 10, longestEffectiveRange: nil, in: NSMakeRange(9, 10)) let redColor = firstCharAttributes[NSAttributedString.Key.foregroundColor] as? Color let yellowColor = lastCharAttributes[NSAttributedString.Key.backgroundColor] as? Color XCTAssertTrue(s1 !== s4) XCTAssertNotNil(redColor) XCTAssertNotNil(yellowColor) XCTAssertTrue(redColor! == .red) XCTAssertTrue(yellowColor! == .yellow) XCTAssertTrue(s4.string == "Hello World") #else let s1 = NSMutableAttributedString(string: "Hello", attributes: [NSAttributedStringKey("key1"): "A"]) let s2 = NSMutableAttributedString(string: " ") let s3 = NSMutableAttributedString(string: "World", attributes: [NSAttributedStringKey("key2"): "B"]) let s4 = s1 + s2 + s3 let firstCharAttributes = s4 .attributes(at: 0, effectiveRange: nil) let lastCharAttributes = s4 .attributes(at: 9, effectiveRange: nil) let a = firstCharAttributes[NSAttributedStringKey("key1")] as? String let b = lastCharAttributes[NSAttributedStringKey("key2")] as? String XCTAssertNotNil(a) XCTAssertNotNil(b) XCTAssertEqual(a, "A") XCTAssertEqual(b, "B") XCTAssertTrue(s4.string == "Hello World") #endif } /// addition between NSMutableAttributedStrings and NSAttributedString do { #if !os(Linux) let s1 = NSMutableAttributedString(string: "Hello", attributes: [NSAttributedString.Key.foregroundColor: Color.red]) let s2 = NSMutableAttributedString(string: " ") let s3 = NSAttributedString(string: "World", attributes: [NSAttributedString.Key.backgroundColor: Color.yellow]) let s4 = s1 + s2 + s3 let firstCharAttributes = s4.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, 0)) let lastCharAttributes = s4.attributes(at: 10, longestEffectiveRange: nil, in: NSMakeRange(9, 10)) let redColor = firstCharAttributes[NSAttributedString.Key.foregroundColor] as? Color let yellowColor = lastCharAttributes[NSAttributedString.Key.backgroundColor] as? Color XCTAssertTrue(s1 !== s4) XCTAssertNotNil(redColor) XCTAssertNotNil(yellowColor) XCTAssertTrue(redColor! == .red) XCTAssertTrue(yellowColor! == .yellow) XCTAssertTrue(s4.string == "Hello World") #else let s1 = NSMutableAttributedString(string: "Hello", attributes: [NSAttributedStringKey("key1"): "A"]) let s2 = NSMutableAttributedString(string: " ") let s3 = NSAttributedString(string: "World", attributes: [NSAttributedStringKey("key2"): "B"]) let s4 = s1 + s2 + s3 let firstCharAttributes = s4 .attributes(at: 0, effectiveRange: nil) let lastCharAttributes = s4 .attributes(at: 9, effectiveRange: nil) let a = firstCharAttributes[NSAttributedStringKey("key1")] as? String let b = lastCharAttributes[NSAttributedStringKey("key2")] as? String XCTAssertNotNil(a) XCTAssertNotNil(b) XCTAssertEqual(a, "A") XCTAssertEqual(b, "B") XCTAssertTrue(s4.string == "Hello World") #endif } /// addition between NSAttributedStrings and NSMutableAttributedString do { #if !os(Linux) let s1 = NSAttributedString(string: "Hello", attributes: [NSAttributedString.Key.foregroundColor: Color.red]) let s2 = NSMutableAttributedString(string: " ") let s3 = NSAttributedString(string: "World", attributes: [NSAttributedString.Key.backgroundColor: Color.yellow]) let s4 = s1 + s2 + s3 let firstCharAttributes = s4.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, 0)) let lastCharAttributes = s4.attributes(at: 10, longestEffectiveRange: nil, in: NSMakeRange(9, 10)) let redColor = firstCharAttributes[NSAttributedString.Key.foregroundColor] as? Color let yellowColor = lastCharAttributes[NSAttributedString.Key.backgroundColor] as? Color XCTAssertTrue(s1 !== s4) XCTAssertNotNil(redColor) XCTAssertNotNil(yellowColor) XCTAssertTrue(redColor! == .red) XCTAssertTrue(yellowColor! == .yellow) XCTAssertTrue(s4.string == "Hello World") #else let s1 = NSAttributedString(string: "Hello", attributes: [NSAttributedStringKey("key1"): "A"]) let s2 = NSMutableAttributedString(string: " ") let s3 = NSAttributedString(string: "World", attributes: [NSAttributedStringKey("key2"): "B"]) let s4 = s1 + s2 + s3 let firstCharAttributes = s4 .attributes(at: 0, effectiveRange: nil) let lastCharAttributes = s4 .attributes(at: 9, effectiveRange: nil) let a = firstCharAttributes[NSAttributedStringKey("key1")] as? String let b = lastCharAttributes[NSAttributedStringKey("key2")] as? String XCTAssertNotNil(a) XCTAssertNotNil(b) XCTAssertEqual(a, "A") XCTAssertEqual(b, "B") XCTAssertTrue(s4.string == "Hello World") #endif } /// addition between NSAttributedString, String and NSMutableAttributedString do { #if !os(Linux) let s1 = NSAttributedString(string: "Hello", attributes: [NSAttributedString.Key.foregroundColor: Color.red]) let s2 = " " let s3 = NSMutableAttributedString(string: "World", attributes: [NSAttributedString.Key.backgroundColor: Color.yellow]) let s4 = s1 + s2 + s3 let firstCharAttributes = s4.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, 0)) let lastCharAttributes = s4.attributes(at: 10, longestEffectiveRange: nil, in: NSMakeRange(9, 10)) let redColor = firstCharAttributes[NSAttributedString.Key.foregroundColor] as? Color let yellowColor = lastCharAttributes[NSAttributedString.Key.backgroundColor] as? Color XCTAssertTrue(s1 !== s4) XCTAssertNotNil(redColor) XCTAssertNotNil(yellowColor) XCTAssertTrue(redColor! == .red) XCTAssertTrue(yellowColor! == .yellow) XCTAssertTrue(s4.string == "Hello World") #else let s1 = NSAttributedString(string: "Hello", attributes: [NSAttributedStringKey("key1"): "A"]) let s2 = " " let s3 = NSMutableAttributedString(string: "World", attributes: [NSAttributedStringKey("key2"): "B"]) let s4 = s1 + s2 + s3 let firstCharAttributes = s4 .attributes(at: 0, effectiveRange: nil) let lastCharAttributes = s4 .attributes(at: 9, effectiveRange: nil) let a = firstCharAttributes[NSAttributedStringKey("key1")] as? String let b = lastCharAttributes[NSAttributedStringKey("key2")] as? String XCTAssertNotNil(a) XCTAssertNotNil(b) XCTAssertEqual(a, "A") XCTAssertEqual(b, "B") XCTAssertTrue(s4.string == "Hello World") #endif } /// addition between NSMutableAttributedString and String do { #if !os(Linux) let s1 = "Hello" let s2 = " " let s3 = NSMutableAttributedString(string: "World", attributes: [NSAttributedString.Key.backgroundColor: Color.yellow]) let s4 = s1 + s2 + s3 let firstCharAttributes = s4.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, 0)) let lastCharAttributes = s4.attributes(at: 10, longestEffectiveRange: nil, in: NSMakeRange(9, 10)) let yellowColor = lastCharAttributes[NSAttributedString.Key.backgroundColor] as? Color XCTAssertTrue(firstCharAttributes.isEmpty) XCTAssertNotNil(yellowColor) XCTAssertTrue(yellowColor! == .yellow) XCTAssertTrue(s4.string == "Hello World") #endif } } func testCompoundAddition() { #if !os(Linux) do { let s = NSMutableAttributedString(string: "Hello", attributes: [NSAttributedString.Key.foregroundColor: Color.red]) s += " " s += NSAttributedString(string: "World", attributes: [NSAttributedString.Key.backgroundColor: Color.yellow]) let firstCharAttributes = s.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, 0)) let lastCharAttributes = s.attributes(at: 10, longestEffectiveRange: nil, in: NSMakeRange(9, 10)) let redColor = firstCharAttributes[NSAttributedString.Key.foregroundColor] as? Color let yellowColor = lastCharAttributes[NSAttributedString.Key.backgroundColor] as? Color XCTAssertNotNil(redColor) XCTAssertNotNil(yellowColor) XCTAssertTrue(redColor! == .red) XCTAssertTrue(yellowColor! == .yellow) XCTAssertTrue(s.string == "Hello World") } do { let s = NSMutableAttributedString(string: "Hello", attributes: [NSAttributedString.Key.foregroundColor: Color.red]) s += NSMutableAttributedString(string: " ") s += NSAttributedString(string: "World", attributes: [NSAttributedString.Key.backgroundColor: Color.yellow]) let firstCharAttributes = s.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, 0)) let lastCharAttributes = s.attributes(at: 10, longestEffectiveRange: nil, in: NSMakeRange(9, 10)) let redColor = firstCharAttributes[NSAttributedString.Key.foregroundColor] as? Color let yellowColor = lastCharAttributes[NSAttributedString.Key.backgroundColor] as? Color XCTAssertNotNil(redColor) XCTAssertNotNil(yellowColor) XCTAssertTrue(redColor! == .red) XCTAssertTrue(yellowColor! == .yellow) XCTAssertTrue(s.string == "Hello World") } #else do { let s = NSMutableAttributedString(string: "Hello", attributes: [NSAttributedStringKey("key1"): "A"]) s += " " s += NSAttributedString(string: "World", attributes: [NSAttributedStringKey("key2"): "B"]) let firstCharAttributes = s.attributes(at: 0, effectiveRange: nil) let lastCharAttributes = s.attributes(at: 9, effectiveRange: nil) let a = firstCharAttributes[NSAttributedStringKey("key1")] as? String let b = lastCharAttributes[NSAttributedStringKey("key2")] as? String XCTAssertNotNil(a) XCTAssertNotNil(b) XCTAssertEqual(a, "A") XCTAssertEqual(b, "B") XCTAssertTrue(s.string == "Hello World") } do { let s = NSMutableAttributedString(string: "Hello", attributes: [NSAttributedStringKey("key1"): "A"]) s += NSMutableAttributedString(string: " ") s += NSAttributedString(string: "World", attributes: [NSAttributedStringKey("key2"): "B"]) let firstCharAttributes = s.attributes(at: 0, effectiveRange: nil) let lastCharAttributes = s.attributes(at: 9, effectiveRange: nil) let a = firstCharAttributes[NSAttributedStringKey("key1")] as? String let b = lastCharAttributes[NSAttributedStringKey("key2")] as? String XCTAssertNotNil(a) XCTAssertNotNil(b) XCTAssertEqual(a, "A") XCTAssertEqual(b, "B") XCTAssertTrue(s.string == "Hello World") } #endif } }
mit
c3ffea58b198ff0c19abdc90e99a1085
42.164804
137
0.69404
4.664353
false
true
false
false
dreamsxin/swift
test/IRGen/associated_type_witness.swift
8
11846
// RUN: %target-swift-frontend -primary-file %s -emit-ir > %t.ll // RUN: FileCheck %s -check-prefix=GLOBAL < %t.ll // RUN: FileCheck %s < %t.ll // REQUIRES: CPU=x86_64 protocol P {} protocol Q {} protocol Assocked { associatedtype Assoc : P, Q } struct Universal : P, Q {} // Witness table access functions for Universal : P and Universal : Q. // CHECK-LABEL: define hidden i8** @_TWaV23associated_type_witness9UniversalS_1PS_() // CHECK: ret i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_TWPV23associated_type_witness9UniversalS_1PS_, i32 0, i32 0) // CHECK-LABEL: define hidden i8** @_TWaV23associated_type_witness9UniversalS_1QS_() // CHECK: ret i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_TWPV23associated_type_witness9UniversalS_1QS_, i32 0, i32 0) // Witness table for WithUniversal : Assocked. // GLOBAL-LABEL: @_TWPV23associated_type_witness13WithUniversalS_8AssockedS_ = hidden constant [3 x i8*] [ // GLOBAL-SAME: i8* bitcast (%swift.type* ()* @_TMaV23associated_type_witness9Universal to i8*) // GLOBAL-SAME: i8* bitcast (i8** ()* @_TWaV23associated_type_witness9UniversalS_1PS_ to i8*) // GLOBAL-SAME: i8* bitcast (i8** ()* @_TWaV23associated_type_witness9UniversalS_1QS_ to i8*) // GLOBAL-SAME: ] struct WithUniversal : Assocked { typealias Assoc = Universal } // Witness table for GenericWithUniversal : Assocked. // GLOBAL-LABEL: @_TWPurGV23associated_type_witness20GenericWithUniversalx_S_8AssockedS_ = hidden constant [3 x i8*] [ // GLOBAL-SAME: i8* bitcast (%swift.type* ()* @_TMaV23associated_type_witness9Universal to i8*) // GLOBAL-SAME: i8* bitcast (i8** ()* @_TWaV23associated_type_witness9UniversalS_1PS_ to i8*) // GLOBAL-SAME: i8* bitcast (i8** ()* @_TWaV23associated_type_witness9UniversalS_1QS_ to i8*) // GLOBAL-SAME: ] struct GenericWithUniversal<T> : Assocked { typealias Assoc = Universal } // Witness table for Fulfilled : Assocked. // GLOBAL-LABEL: @_TWPuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_ = hidden constant [3 x i8*] [ // GLOBAL-SAME: i8* bitcast (%swift.type* (%swift.type*, i8**)* @_TWtuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5Assoc to i8*) // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_TWTuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5AssocPS_1P_ to i8*) // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_TWTuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5AssocPS_1Q_ to i8*) // GLOBAL-SAME: ] struct Fulfilled<T : protocol<P, Q> > : Assocked { typealias Assoc = T } // Associated type metadata access function for Fulfilled.Assoc. // CHECK-LABEL: define internal %swift.type* @_TWtuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5Assoc(%swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked") // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to %swift.type** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i64 3 // CHECK-NEXT: [[T2:%.*]] = load %swift.type*, %swift.type** [[T1]], align 8, !invariant.load // CHECK-NEXT: ret %swift.type* [[T2]] // Associated type witness table access function for Fulfilled.Assoc : P. // CHECK-LABEL: define internal i8** @_TWTuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5AssocPS_1P_(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked") // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8*** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 4 // CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load // CHECK-NEXT: ret i8** [[T2]] // Associated type witness table access function for Fulfilled.Assoc : Q. // CHECK-LABEL: define internal i8** @_TWTuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5AssocPS_1Q_(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked") // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8*** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 5 // CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load // CHECK-NEXT: ret i8** [[T2]] struct Pair<T, U> : P, Q {} // Generic witness table pattern for Computed : Assocked. // GLOBAL-LABEL: @_TWPu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_ = hidden constant [3 x i8*] [ // GLOBAL-SAME: i8* bitcast (%swift.type* (%swift.type*, i8**)* @_TWtu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_5Assoc to i8*) // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_TWTu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_5AssocPS_1P_ to i8*) // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_TWTu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_5AssocPS_1Q_ to i8*) // GLOBAL-SAME: ] // Generic witness table cache for Computed : Assocked. // GLOBAL-LABEL: @_TWGu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_ = internal global %swift.generic_witness_table_cache { // GLOBAL-SAME: i16 3, // GLOBAL-SAME: i16 1, // Relative reference to protocol // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (%swift.protocol* @_TMp23associated_type_witness8Assocked to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_TWGu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_, i32 0, i32 2) to i64)) to i32) // Relative reference to witness table template // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([3 x i8*]* @_TWPu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_ to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_TWGu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_, i32 0, i32 3) to i64)) to i32), // No instantiator function // GLOBAL-SAME: i32 0, // GLOBAL-SAME: [16 x i8*] zeroinitializer // GLOBAL-SAME: } struct Computed<T, U> : Assocked { typealias Assoc = Pair<T, U> } // Associated type metadata access function for Computed.Assoc. // CHECK-LABEL: define internal %swift.type* @_TWtu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_5Assoc(%swift.type* %"Computed<T, U>", i8** %"Computed<T, U>.Assocked") // CHECK: entry: // CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** %"Computed<T, U>.Assocked", i32 -1 // CHECK-NEXT: [[CACHE:%.*]] = bitcast i8** [[T0]] to %swift.type** // CHECK-NEXT: [[CACHE_RESULT:%.*]] = load %swift.type*, %swift.type** [[CACHE]], align 8 // CHECK-NEXT: [[T1:%.*]] = icmp eq %swift.type* [[CACHE_RESULT]], null // CHECK-NEXT: br i1 [[T1]], label %fetch, label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi %swift.type* [ [[CACHE_RESULT]], %entry ], [ [[FETCH_RESULT:%.*]], %fetch ] // CHECK-NEXT: ret %swift.type* [[T0]] // CHECK: fetch: // CHECK-NEXT: [[T0:%.*]] = bitcast %swift.type* %"Computed<T, U>" to %swift.type** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i64 3 // CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T1]], align 8, !invariant.load // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Computed<T, U>" to %swift.type** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i64 4 // CHECK-NEXT: [[U:%.*]] = load %swift.type*, %swift.type** [[T1]], align 8, !invariant.load // CHECK-NEXT: [[FETCH_RESULT]] = call %swift.type* @_TMaV23associated_type_witness4Pair(%swift.type* [[T]], %swift.type* [[U]]) // CHECK-NEXT: store atomic %swift.type* [[FETCH_RESULT]], %swift.type** [[CACHE]] release, align 8 // CHECK-NEXT: br label %cont // Witness table instantiation function for Computed : Assocked. // CHECK-LABEL: define hidden i8** @_TWauRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_(%swift.type*) // CHECK: entry: // CHECK-NEXT: [[WTABLE:%.*]] = call i8** @rt_swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_, %swift.type* %0, i8** null) // CHECK-NEXT: ret i8** [[WTABLE]] struct PBox<T: P> {} protocol HasSimpleAssoc { associatedtype Assoc } protocol DerivedFromSimpleAssoc : HasSimpleAssoc {} // Generic witness table pattern for GenericComputed : DerivedFromSimpleAssoc. // GLOBAL-LABEL: @_TWPuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_ = hidden constant [1 x i8*] zeroinitializer // Generic witness table cache for GenericComputed : DerivedFromSimpleAssoc. // GLOBAL-LABEL: @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_ = internal global %swift.generic_witness_table_cache { // GLOBAL-SAME: i16 1, // GLOBAL-SAME: i16 0, // Relative reference to protocol // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (%swift.protocol* @_TMp23associated_type_witness22DerivedFromSimpleAssoc to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_, i32 0, i32 2) to i64)) to i32) // Relative reference to witness table template // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x i8*]* @_TWPuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_ to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_, i32 0, i32 3) to i64)) to i32), // Relative reference to instantiator function // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (void (i8**, %swift.type*, i8**)* @_TWIuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_ to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_, i32 0, i32 4) to i64)) to i32), // GLOBAL-SAME: [16 x i8*] zeroinitializer // GLOBAL-SAME: } struct GenericComputed<T: P> : DerivedFromSimpleAssoc { typealias Assoc = PBox<T> } // Instantiation function for GenericComputed : DerivedFromSimpleAssoc. // CHECK-LABEL: define internal void @_TWIuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_(i8**, %swift.type*, i8**) // CHECK: [[T0:%.*]] = call i8** @_TWauRx23associated_type_witness1PrGVS_15GenericComputedx_S_14HasSimpleAssocS_(%swift.type* %1) // CHECK-NEXT: [[T1:%.*]] = bitcast i8** [[T0]] to i8* // CHECK-NEXT: [[T2:%.*]] = getelementptr inbounds i8*, i8** %0, i32 0 // CHECK-NEXT: store i8* [[T1]], i8** [[T2]], align 8 // CHECK-NEXT: ret void // Witness table instantiation function for GenericComputed : HasSimpleAssoc.. // CHECK-LABEL: define hidden i8** @_TWauRx23associated_type_witness1PrGVS_15GenericComputedx_S_14HasSimpleAssocS_(%swift.type*) // CHECK-NEXT: entry: // CHECK-NEXT: [[WTABLE:%.*]] = call i8** @rt_swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_14HasSimpleAssocS_, %swift.type* %0, i8** null) // CHECK-NEXT: ret i8** %1 protocol HasAssocked { associatedtype Contents : Assocked } struct FulfilledFromAssociatedType<T : HasAssocked> : HasSimpleAssoc { typealias Assoc = PBox<T.Contents.Assoc> } struct UsesVoid : HasSimpleAssoc { typealias Assoc = () }
apache-2.0
c48e19bbcd4b5b6802c70a5e747c56d6
67.08046
418
0.692977
3.275996
false
false
false
false
benlangmuir/swift
test/Concurrency/Runtime/effectful_properties.swift
7
3129
// RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime enum GeneralError : Error { case UnknownBallKind case Todo } enum BallKind { case MostLostV1 case Chromehard case PT5 case KirksandLignature } @available(SwiftStdlib 5.1, *) class Specs { // obtains the number of dimples subscript(_ bk : BallKind) -> Int { get throws { switch (bk) { case .MostLostV1: return 450 case .Chromehard: return 125 default: throw GeneralError.UnknownBallKind } } } } @available(SwiftStdlib 5.1, *) actor Database { var currentData : Specs { get async { let handle = detach { Specs() } print("obtaining specs...") return await handle.get() } } var hasNewData : Bool { get throws { return true } } } @available(SwiftStdlib 5.1, *) protocol SphericalObject { var name : String { get async throws } var dimples : Int { get async throws } var description : String { get async throws } } @available(SwiftStdlib 5.1, *) class Ball : SphericalObject { var name : String { get async throws { throw GeneralError.Todo } } var dimples : Int { get async throws { throw GeneralError.Todo } } var description : String { get async throws { throw GeneralError.Todo } } } @available(SwiftStdlib 5.1, *) class GolfBall : Ball { private static let db : Database = Database() private var _model : BallKind private var _dimples : Int? init(_ bk : BallKind) { _model = bk } override var name : String { return "golf ball" } override var description : String { get async throws { return "this \(name) has \(await dimples) dimples" } } override var dimples : Int { get async { let newData = (try? await GolfBall.db.hasNewData) ?? false if newData || _dimples == nil { let specs = await GolfBall.db.currentData _dimples = (try? specs[_model]) ?? 0 } return _dimples! } } } // CHECK: obtaining specs... // CHECK: this golf ball has 450 dimples // CHECK: obtaining specs... // CHECK: this golf ball has 125 dimples // CHECK: obtaining specs... // CHECK: this golf ball has 0 dimples // CHECK: obtaining specs... // CHECK: this golf ball has 0 dimples @available(SwiftStdlib 5.1, *) func printAsBall(_ b : Ball) async { print(try! await b.description) } @available(SwiftStdlib 5.1, *) func printAsAsSphericalObject(_ b : SphericalObject) async { print(try! await b.description) } @available(SwiftStdlib 5.1, *) @main struct RunIt { static func main() async { let balls : [(Bool, Ball)] = [ (true, GolfBall(.MostLostV1)), (false, GolfBall(.Chromehard)), (true, GolfBall(.PT5)), (false, GolfBall(.KirksandLignature)) ] for (useProtocol, ball) in balls { if (useProtocol) { await printAsAsSphericalObject(ball) } else { await printAsBall(ball) } } } }
apache-2.0
87ddac360c7b9f9b96501dd20e30764f
21.510791
109
0.64046
3.751799
false
false
false
false
benlangmuir/swift
test/Profiler/coverage_ternary.swift
2
1317
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_ternary %s | %FileCheck %s // RUN: %target-swift-frontend -profile-generate -profile-coverage-mapping -emit-ir %s // coverage_ternary.bar.init() -> coverage_ternary.bar // CHECK-LABEL: sil hidden @$s16coverage_ternary3barCACycfc // CHECK-NOT: return // CHECK: increment_profiler_counter // rdar://problem/23256795 - Avoid crash if an if_expr has no parent // CHECK: sil_coverage_map {{.*}}// variable initialization expression of coverage_ternary.bar.m1 : Swift.String class bar { var m1 = flag == 0 // CHECK: [[@LINE]]:12 -> [[@LINE+2]]:22 : 0 ? "false" // CHECK: [[@LINE]]:16 -> [[@LINE]]:23 : 1 : "true"; // CHECK: [[@LINE]]:16 -> [[@LINE]]:22 : (0 - 1) } // Note: We didn't instantiate bar, but we still expect to see instrumentation // for its *structors, and coverage mapping information for it. var flag: Int = 0 // CHECK-LABEL: sil_coverage_map {{.*}}// coverage_ternary.foo func foo(_ x : Int32) -> Int32 { // CHECK: [[@LINE]]:32 -> [[@LINE+4]]:2 : 0 return x == 3 ? 9000 // CHECK: [[@LINE]]:16 -> [[@LINE]]:20 : 1 : 1234 // CHECK: [[@LINE]]:16 -> [[@LINE]]:20 : (0 - 1) } foo(1) foo(2) foo(3)
apache-2.0
c84c252ffc8d3ab01af53b4ffa987231
41.483871
176
0.617312
3.31738
false
false
false
false
benlangmuir/swift
SwiftCompilerSources/Sources/Basic/SourceLoc.swift
5
2051
//===--- SourceLoc.swift - SourceLoc bridging utilities ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import ASTBridging public struct SourceLoc { /// Points into a source file. let locationInFile: UnsafePointer<UInt8> public init?(locationInFile: UnsafePointer<UInt8>?) { guard let locationInFile = locationInFile else { return nil } self.locationInFile = locationInFile } public init?(bridged: swift.SourceLoc) { guard bridged.isValid() else { return nil } self.locationInFile = bridged.__getOpaquePointerValueUnsafe().assumingMemoryBound(to: UInt8.self) } public var bridged: swift.SourceLoc { .init(llvm.SMLoc.getFromPointer(locationInFile)) } } extension SourceLoc { public func advanced(by n: Int) -> SourceLoc { SourceLoc(locationInFile: locationInFile.advanced(by: n))! } } extension Optional where Wrapped == SourceLoc { public var bridged: swift.SourceLoc { self?.bridged ?? .init() } } public struct CharSourceRange { private let start: SourceLoc private let byteLength: UInt32 public init(start: SourceLoc, byteLength: UInt32) { self.start = start self.byteLength = byteLength } public init?(bridged: swift.CharSourceRange) { guard let start = SourceLoc(bridged: bridged.__getStartUnsafe()) else { return nil } self.init(start: start, byteLength: bridged.getByteLength()) } public var bridged: swift.CharSourceRange { .init(start.bridged, byteLength) } } extension Optional where Wrapped == CharSourceRange { public var bridged: swift.CharSourceRange { self?.bridged ?? .init(.init(), 0) } }
apache-2.0
5967430f412eb7bc5ee70879b133fa9c
26.346667
101
0.673818
4.458696
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Extensions/DynamoDB/DynamoDBEncoder.swift
1
15931
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Foundation public class DynamoDBEncoder { public var userInfo: [CodingUserInfoKey: Any] = [:] public init() {} public func encode<T: Encodable>(_ value: T) throws -> [String: DynamoDB.AttributeValue] { let encoder = _DynamoDBEncoder(userInfo: userInfo) try value.encode(to: encoder) return try encoder.storage.collapse() } } private protocol _EncoderContainer { var attribute: DynamoDB.AttributeValue { get } } /// class for holding a keyed container (dictionary). Need to encapsulate dictionary in class so we can be sure we are /// editing the dictionary we push onto the stack private class _EncoderKeyedContainer: _EncoderContainer { private(set) var values: [String: DynamoDB.AttributeValue] = [:] private(set) var nestedContainers: [String: _EncoderContainer] = [:] func addChild(path: String, child: DynamoDB.AttributeValue) { self.values[path] = child } func addNestedContainer(path: String, child: _EncoderContainer) { self.nestedContainers[path] = child } func copy(to: _EncoderKeyedContainer) { to.values = self.values to.nestedContainers = self.nestedContainers } var attribute: DynamoDB.AttributeValue { // merge child values, plus nested containers let values = self.values.merging(self.nestedContainers.mapValues { $0.attribute }) { rt, _ in return rt } return .m(values) } } /// class for holding unkeyed container (array). Need to encapsulate array in class so we can be sure we are /// editing the array we push onto the stack private class _EncoderUnkeyedContainer: _EncoderContainer { private(set) var values: [DynamoDB.AttributeValue] = [] private(set) var nestedContainers: [_EncoderContainer] = [] func addChild(_ child: DynamoDB.AttributeValue) { self.values.append(child) } func addNestedContainer(_ child: _EncoderContainer) { self.nestedContainers.append(child) } var attribute: DynamoDB.AttributeValue { // merge child values, plus nested containers let values = self.values + self.nestedContainers.map { $0.attribute } return .l(values) } } /// struct for holding a single attribute value. private struct _EncoderSingleValueContainer: _EncoderContainer { let attribute: DynamoDB.AttributeValue } /// storage for DynamoDB Encoder. Stores a stack of encoder containers private struct _EncoderStorage { /// the container stack private var containers: [_EncoderContainer] = [] /// initializes self with no containers init() {} /// push a new container onto the storage mutating func pushKeyedContainer() -> _EncoderKeyedContainer { let container = _EncoderKeyedContainer() containers.append(container) return container } /// push a new container onto the storage mutating func pushUnkeyedContainer() -> _EncoderUnkeyedContainer { let container = _EncoderUnkeyedContainer() containers.append(container) return container } mutating func pushSingleValueContainer(_ attribute: DynamoDB.AttributeValue) { let container = _EncoderSingleValueContainer(attribute: attribute) containers.append(container) } /// pop a container from the storage @discardableResult mutating func popContainer() -> _EncoderContainer { return self.containers.removeLast() } func collapse() throws -> [String: DynamoDB.AttributeValue] { assert(self.containers.count == 1) guard case .m(let values) = self.containers.first?.attribute else { throw DynamoDBEncoderError.topLevelArray } return values } } class _DynamoDBEncoder: Encoder { var codingPath: [CodingKey] var userInfo: [CodingUserInfoKey: Any] fileprivate var storage: _EncoderStorage init(userInfo: [CodingUserInfoKey: Any], codingPath: [CodingKey] = []) { self.codingPath = codingPath self.userInfo = userInfo self.storage = _EncoderStorage() } func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey { let container = self.storage.pushKeyedContainer() return KeyedEncodingContainer(KEC(container: container, encoder: self)) } func unkeyedContainer() -> UnkeyedEncodingContainer { let container = self.storage.pushUnkeyedContainer() return UKEC(container: container, encoder: self) } func singleValueContainer() -> SingleValueEncodingContainer { return self } fileprivate struct KEC<Key: CodingKey>: KeyedEncodingContainerProtocol { var codingPath: [CodingKey] let container: _EncoderKeyedContainer let encoder: _DynamoDBEncoder internal init(container: _EncoderKeyedContainer, encoder: _DynamoDBEncoder) { self.container = container self.encoder = encoder self.codingPath = encoder.codingPath } mutating func encode(_ attribute: DynamoDB.AttributeValue, forKey key: Key) { self.container.addChild(path: key.stringValue, child: attribute) } mutating func encodeNil(forKey key: Key) throws { self.encode(.null(true), forKey: key) } mutating func encode(_ value: Bool, forKey key: Key) throws { self.encode(.bool(value), forKey: key) } mutating func encode(_ value: String, forKey key: Key) throws { self.encode(.s(value), forKey: key) } mutating func encode(_ value: Double, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: Float, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: Int, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: Int8, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: Int16, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: Int32, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: Int64, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: UInt, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: UInt8, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: UInt16, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: UInt32, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode(_ value: UInt64, forKey key: Key) throws { self.encode(.n(value.description), forKey: key) } mutating func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } let attribute = try encoder.box(value) self.encode(attribute, forKey: key) } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } let nestedContainer = _EncoderKeyedContainer() container.addNestedContainer(path: key.stringValue, child: nestedContainer) return KeyedEncodingContainer(KEC<NestedKey>(container: nestedContainer, encoder: self.encoder)) } mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } let nestedContainer = _EncoderUnkeyedContainer() container.addNestedContainer(path: key.stringValue, child: nestedContainer) return UKEC(container: nestedContainer, encoder: self.encoder) } func _superEncoder(forKey key: CodingKey) -> Encoder { self.encoder.codingPath.append(key) defer { self.encoder.codingPath.removeLast() } let nestedContainer = _EncoderKeyedContainer() container.addNestedContainer(path: key.stringValue, child: nestedContainer) return _DynamoDBReferencingEncoder(encoder: self.encoder, container: nestedContainer) } mutating func superEncoder() -> Encoder { return self._superEncoder(forKey: DynamoDBCodingKey.super) } mutating func superEncoder(forKey key: Key) -> Encoder { return self._superEncoder(forKey: key) } } fileprivate struct UKEC: UnkeyedEncodingContainer { var codingPath: [CodingKey] var count: Int let container: _EncoderUnkeyedContainer let encoder: _DynamoDBEncoder internal init(container: _EncoderUnkeyedContainer, encoder: _DynamoDBEncoder) { self.container = container self.encoder = encoder self.codingPath = encoder.codingPath self.count = 0 } mutating func encode(_ attribute: DynamoDB.AttributeValue) { self.container.addChild(attribute) self.count += 1 } mutating func encodeNil() throws { self.encode(.null(true)) } mutating func encode(_ value: Bool) throws { self.encode(.bool(value)) } mutating func encode(_ value: String) throws { self.encode(.s(value)) } mutating func encode(_ value: Double) throws { self.encode(.n(value.description)) } mutating func encode(_ value: Float) throws { self.encode(.n(value.description)) } mutating func encode(_ value: Int) throws { self.encode(.n(value.description)) } mutating func encode(_ value: Int8) throws { self.encode(.n(value.description)) } mutating func encode(_ value: Int16) throws { self.encode(.n(value.description)) } mutating func encode(_ value: Int32) throws { self.encode(.n(value.description)) } mutating func encode(_ value: Int64) throws { self.encode(.n(value.description)) } mutating func encode(_ value: UInt) throws { self.encode(.n(value.description)) } mutating func encode(_ value: UInt8) throws { self.encode(.n(value.description)) } mutating func encode(_ value: UInt16) throws { self.encode(.n(value.description)) } mutating func encode(_ value: UInt32) throws { self.encode(.n(value.description)) } mutating func encode(_ value: UInt64) throws { self.encode(.n(value.description)) } mutating func encode<T>(_ value: T) throws where T: Encodable { let attribute = try encoder.box(value) self.encode(attribute) } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { self.encoder.codingPath.append(DynamoDBCodingKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.count += 1 let nestedContainer = _EncoderKeyedContainer() container.addNestedContainer(nestedContainer) return KeyedEncodingContainer(KEC<NestedKey>(container: nestedContainer, encoder: self.encoder)) } mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self.encoder.codingPath.append(DynamoDBCodingKey(index: self.count)) defer { self.encoder.codingPath.removeLast() } self.count += 1 let nestedContainer = _EncoderUnkeyedContainer() container.addNestedContainer(nestedContainer) return UKEC(container: nestedContainer, encoder: self.encoder) } mutating func superEncoder() -> Encoder { preconditionFailure("Attaching a superDecoder to a unkeyed container is unsupported") } } } extension _DynamoDBEncoder: SingleValueEncodingContainer { func encode(_ attribute: DynamoDB.AttributeValue) { self.storage.pushSingleValueContainer(attribute) } func encodeNil() throws { self.encode(.null(true)) } func encode(_ value: Bool) throws { self.encode(.bool(value)) } func encode(_ value: String) throws { self.encode(.s(value)) } func encode(_ value: Double) throws { self.encode(.n(value.description)) } func encode(_ value: Float) throws { self.encode(.n(value.description)) } func encode(_ value: Int) throws { self.encode(.n(value.description)) } func encode(_ value: Int8) throws { self.encode(.n(value.description)) } func encode(_ value: Int16) throws { self.encode(.n(value.description)) } func encode(_ value: Int32) throws { self.encode(.n(value.description)) } func encode(_ value: Int64) throws { self.encode(.n(value.description)) } func encode(_ value: UInt) throws { self.encode(.n(value.description)) } func encode(_ value: UInt8) throws { self.encode(.n(value.description)) } func encode(_ value: UInt16) throws { self.encode(.n(value.description)) } func encode(_ value: UInt32) throws { self.encode(.n(value.description)) } func encode(_ value: UInt64) throws { self.encode(.n(value.description)) } func encode<T>(_ value: T) throws where T: Encodable { let attribute = try box(value) encode(attribute) } } extension _DynamoDBEncoder { func box(_ data: Data) throws -> DynamoDB.AttributeValue { return .b(data) } func box(_ value: Encodable) throws -> DynamoDB.AttributeValue { let type = Swift.type(of: value) if type == Data.self || type == NSData.self { return try self.box(value as! Data) } else { try value.encode(to: self) return self.storage.popContainer().attribute } } } // MARK: DynamoDBEncoderError public enum DynamoDBEncoderError: Error { case topLevelArray } // MARK: Referencing Encoder private class _DynamoDBReferencingEncoder: _DynamoDBEncoder { let container: _EncoderKeyedContainer init(encoder: _DynamoDBEncoder, container: _EncoderKeyedContainer) { self.container = container super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath) } deinit { (storage.popContainer() as? _EncoderKeyedContainer)?.copy(to: container) } }
apache-2.0
84c4adca65a48ad6adf1df0f167f8eff
31.512245
164
0.629967
4.830503
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Extensions/DynamoDB/DynamoDBDecoder.swift
1
27154
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Foundation public class DynamoDBDecoder { public var userInfo: [CodingUserInfoKey: Any] = [:] public init() {} public func decode<T: Decodable>(_ type: T.Type, from attributes: [String: DynamoDB.AttributeValue]) throws -> T { let decoder = _DynamoDBDecoder(referencing: attributes, userInfo: userInfo) let value = try T(from: decoder) return value } } /// storage for Dynamo Decoder. Stores a stack of Attribute values private struct _DecoderStorage { /// the container stack private var attributes: [DynamoDB.AttributeValue] = [] /// initializes self with no containers init(_ attribute: DynamoDB.AttributeValue) { self.attributes.append(attribute) } /// return the attribute at the top of the storage var topAttribute: DynamoDB.AttributeValue { return attributes.last! } /// push a new attribute onto the storage mutating func pushAttribute(_ attribute: DynamoDB.AttributeValue) { self.attributes.append(attribute) } /// pop a attribute from the storage @discardableResult mutating func popAttribute() -> DynamoDB.AttributeValue { return self.attributes.removeLast() } } private class _DynamoDBDecoder: Decoder { var codingPath: [CodingKey] var userInfo: [CodingUserInfoKey: Any] let attributes: [String: DynamoDB.AttributeValue] var storage: _DecoderStorage init(referencing: [String: DynamoDB.AttributeValue], userInfo: [CodingUserInfoKey: Any], codingPath: [CodingKey] = []) { self.codingPath = codingPath self.userInfo = userInfo self.attributes = referencing self.storage = _DecoderStorage(.m(self.attributes)) } func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey { guard case .m(let attributes) = self.storage.topAttribute else { throw DecodingError.dataCorrupted(.init(codingPath: self.codingPath, debugDescription: "Expected to decode a map")) } return KeyedDecodingContainer(KDC(attributes: attributes, decoder: self)) } func unkeyedContainer() throws -> UnkeyedDecodingContainer { return UKDC(attribute: self.storage.topAttribute, decoder: self) } func singleValueContainer() throws -> SingleValueDecodingContainer { return self } struct KDC<Key: CodingKey>: KeyedDecodingContainerProtocol { var codingPath: [CodingKey] var allKeys: [Key] var decoder: _DynamoDBDecoder var attributes: [String: DynamoDB.AttributeValue] init(attributes: [String: DynamoDB.AttributeValue], decoder: _DynamoDBDecoder) { self.decoder = decoder self.attributes = attributes self.codingPath = decoder.codingPath self.allKeys = attributes.keys.compactMap { Key(stringValue: $0) } } func contains(_ key: Key) -> Bool { return self.allKeys.first { $0.stringValue == key.stringValue } != nil } func getValue(forKey key: Key) throws -> DynamoDB.AttributeValue { guard let value = attributes[key.stringValue] else { throw DecodingError.keyNotFound(key, .init(codingPath: self.codingPath, debugDescription: "")) } return value } func decodeNil(forKey key: Key) throws -> Bool { return try self.decoder.unboxNil(self.getValue(forKey: key)) } func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return try self.decoder.unbox(self.getValue(forKey: key), as: Bool.self) } func decode(_ type: String.Type, forKey key: Key) throws -> String { return try self.decoder.unbox(self.getValue(forKey: key), as: String.self) } func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return try self.decoder.unbox(self.getValue(forKey: key), as: Double.self) } func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return try self.decoder.unbox(self.getValue(forKey: key), as: Float.self) } func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return try self.decoder.unbox(self.getValue(forKey: key), as: Int.self) } func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return try self.decoder.unbox(self.getValue(forKey: key), as: Int8.self) } func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return try self.decoder.unbox(self.getValue(forKey: key), as: Int16.self) } func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return try self.decoder.unbox(self.getValue(forKey: key), as: Int32.self) } func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return try self.decoder.unbox(self.getValue(forKey: key), as: Int64.self) } func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return try self.decoder.unbox(self.getValue(forKey: key), as: UInt.self) } func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return try self.decoder.unbox(self.getValue(forKey: key), as: UInt8.self) } func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return try self.decoder.unbox(self.getValue(forKey: key), as: UInt16.self) } func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return try self.decoder.unbox(self.getValue(forKey: key), as: UInt32.self) } func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return try self.decoder.unbox(self.getValue(forKey: key), as: UInt64.self) } func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } return try self.decoder.unbox(self.getValue(forKey: key), as: T.self) } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard case .m(let attributes) = try getValue(forKey: key) else { throw DecodingError.dataCorrupted(.init(codingPath: self.codingPath, debugDescription: "Expected a map")) } return KeyedDecodingContainer(KDC<NestedKey>(attributes: attributes, decoder: self.decoder)) } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } return UKDC(attribute: try self.getValue(forKey: key), decoder: self.decoder) } func _superDecoder(forKey key: CodingKey) throws -> Decoder { self.decoder.codingPath.append(key) defer { self.decoder.codingPath.removeLast() } guard let value = attributes[key.stringValue] else { throw DecodingError.keyNotFound(key, .init(codingPath: self.codingPath, debugDescription: "")) } guard case .m(let attributes) = value else { throw DecodingError.dataCorrupted(.init(codingPath: self.codingPath, debugDescription: "Expected a map attribute")) } return _DynamoDBDecoder(referencing: attributes, userInfo: self.decoder.userInfo, codingPath: self.decoder.codingPath) } func superDecoder() throws -> Decoder { return try self._superDecoder(forKey: DynamoDBCodingKey.super) } func superDecoder(forKey key: Key) throws -> Decoder { return try self._superDecoder(forKey: key) } } struct UKDC: UnkeyedDecodingContainer { var codingPath: [CodingKey] var count: Int? var isAtEnd: Bool { return self.currentIndex >= self.count! } var currentIndex: Int var attribute: DynamoDB.AttributeValue let decoder: _DynamoDBDecoder internal init(attribute: DynamoDB.AttributeValue, decoder: _DynamoDBDecoder) { self.attribute = attribute self.decoder = decoder self.codingPath = decoder.codingPath self.currentIndex = 0 switch attribute { case .l(let values): self.count = values.count case .bs(let values): self.count = values.count case .ns(let values): self.count = values.count case .ss(let values): self.count = values.count default: self.count = 0 } } mutating func getAttributeValue() throws -> DynamoDB.AttributeValue { guard case .l(let values) = self.attribute else { throw DecodingError.typeMismatch(type(of: self.attribute), .init(codingPath: self.codingPath, debugDescription: "Expected DynamoDB.AttributeValue.l")) } let value = values[currentIndex] currentIndex += 1 return value } mutating func getNumberValue() throws -> String { switch self.attribute { case .ns(let values): let value = values[currentIndex] currentIndex += 1 return value case .l(let attributes): let attribute = attributes[currentIndex] guard case .n(let value) = attribute else { throw DecodingError.typeMismatch(type(of: self.attribute), .init(codingPath: self.codingPath, debugDescription: "Expected DynamoDB.AttributeValue.l holding a number attribute")) } self.currentIndex += 1 return value default: throw DecodingError.typeMismatch(type(of: self.attribute), .init(codingPath: self.codingPath, debugDescription: "Expected DynamoDB.AttributeValue.l")) } } mutating func getStringValue() throws -> String { switch self.attribute { case .ss(let values): let value = values[currentIndex] currentIndex += 1 return value case .l(let attributes): let attribute = attributes[currentIndex] guard case .s(let value) = attribute else { throw DecodingError.typeMismatch(type(of: self.attribute), .init(codingPath: self.codingPath, debugDescription: "Expected DynamoDB.AttributeValue.l holding a string attribute")) } self.currentIndex += 1 return value default: throw DecodingError.typeMismatch(type(of: self.attribute), .init(codingPath: self.codingPath, debugDescription: "Expected DynamoDB.AttributeValue.l")) } } mutating func decodeNil() throws -> Bool { guard case .null = try self.getAttributeValue() else { self.currentIndex -= 1 return false } return true } mutating func decode(_: Bool.Type) throws -> Bool { let value = try getAttributeValue() guard case .bool(let boolValue) = value else { throw DecodingError.typeMismatch(Bool.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return boolValue } mutating func decode(_: String.Type) throws -> String { return try self.getStringValue() } mutating func decode(_: Double.Type) throws -> Double { let value = try getNumberValue() guard let unboxValue = Double(value) else { throw DecodingError.typeMismatch(Double.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: Float.Type) throws -> Float { let value = try getNumberValue() guard let unboxValue = Float(value) else { throw DecodingError.typeMismatch(Float.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: Int.Type) throws -> Int { let value = try getNumberValue() guard let unboxValue = Int(value) else { throw DecodingError.typeMismatch(Int.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: Int8.Type) throws -> Int8 { let value = try getNumberValue() guard let unboxValue = Int8(value) else { throw DecodingError.typeMismatch(Int8.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: Int16.Type) throws -> Int16 { let value = try getNumberValue() guard let unboxValue = Int16(value) else { throw DecodingError.typeMismatch(Int16.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: Int32.Type) throws -> Int32 { let value = try getNumberValue() guard let unboxValue = Int32(value) else { throw DecodingError.typeMismatch(Int32.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: Int64.Type) throws -> Int64 { let value = try getNumberValue() guard let unboxValue = Int64(value) else { throw DecodingError.typeMismatch(Int64.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: UInt.Type) throws -> UInt { let value = try getNumberValue() guard let unboxValue = UInt(value) else { throw DecodingError.typeMismatch(UInt.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: UInt8.Type) throws -> UInt8 { let value = try getNumberValue() guard let unboxValue = UInt8(value) else { throw DecodingError.typeMismatch(UInt8.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: UInt16.Type) throws -> UInt16 { let value = try getNumberValue() guard let unboxValue = UInt16(value) else { throw DecodingError.typeMismatch(UInt16.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: UInt32.Type) throws -> UInt32 { let value = try getNumberValue() guard let unboxValue = UInt32(value) else { throw DecodingError.typeMismatch(UInt32.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode(_: UInt64.Type) throws -> UInt64 { let value = try getNumberValue() guard let unboxValue = UInt64(value) else { throw DecodingError.typeMismatch(UInt64.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(value)")) } return unboxValue } mutating func decode<T>(_ type: T.Type) throws -> T where T: Decodable { switch self.attribute { case .bs(let values): let value = values[currentIndex] currentIndex += 1 return try self.decoder.unbox(.b(value), as: T.self) case .ss(let values): let value = values[currentIndex] currentIndex += 1 return try self.decoder.unbox(.s(value), as: T.self) case .ns(let values): let value = values[currentIndex] currentIndex += 1 return try self.decoder.unbox(.n(value), as: T.self) case .l(let values): let value = values[currentIndex] currentIndex += 1 return try self.decoder.unbox(value, as: T.self) default: throw DecodingError.typeMismatch(type, .init(codingPath: self.codingPath, debugDescription: "Expected list attribute")) } } mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey { self.decoder.codingPath.append(DynamoDBCodingKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard case .m(let attributes) = try getAttributeValue() else { throw DecodingError.dataCorrupted(.init(codingPath: self.codingPath, debugDescription: "Expected a map")) } return KeyedDecodingContainer(KDC<NestedKey>(attributes: attributes, decoder: self.decoder)) } mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { self.decoder.codingPath.append(DynamoDBCodingKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } return UKDC(attribute: try self.getAttributeValue(), decoder: self.decoder) } mutating func superDecoder() throws -> Decoder { preconditionFailure("Attaching a superDecoder to a unkeyed container is unsupported") } } } extension _DynamoDBDecoder: SingleValueDecodingContainer { func decodeNil() -> Bool { guard case .null = self.storage.topAttribute else { return false } return true } func decode(_: Bool.Type) throws -> Bool { return try unbox(self.storage.topAttribute, as: Bool.self) } func decode(_: String.Type) throws -> String { return try unbox(self.storage.topAttribute, as: String.self) } func decode(_: Double.Type) throws -> Double { return try unbox(self.storage.topAttribute, as: Double.self) } func decode(_: Float.Type) throws -> Float { return try unbox(self.storage.topAttribute, as: Float.self) } func decode(_: Int.Type) throws -> Int { return try unbox(self.storage.topAttribute, as: Int.self) } func decode(_: Int8.Type) throws -> Int8 { return try unbox(self.storage.topAttribute, as: Int8.self) } func decode(_: Int16.Type) throws -> Int16 { return try unbox(self.storage.topAttribute, as: Int16.self) } func decode(_: Int32.Type) throws -> Int32 { return try unbox(self.storage.topAttribute, as: Int32.self) } func decode(_: Int64.Type) throws -> Int64 { return try unbox(self.storage.topAttribute, as: Int64.self) } func decode(_: UInt.Type) throws -> UInt { return try unbox(self.storage.topAttribute, as: UInt.self) } func decode(_: UInt8.Type) throws -> UInt8 { return try unbox(self.storage.topAttribute, as: UInt8.self) } func decode(_: UInt16.Type) throws -> UInt16 { return try unbox(self.storage.topAttribute, as: UInt16.self) } func decode(_: UInt32.Type) throws -> UInt32 { return try unbox(self.storage.topAttribute, as: UInt32.self) } func decode(_: UInt64.Type) throws -> UInt64 { return try unbox(self.storage.topAttribute, as: UInt64.self) } func decode<T>(_: T.Type) throws -> T where T: Decodable { return try unbox(self.storage.topAttribute, as: T.self) } } extension _DynamoDBDecoder { func unboxNil(_ attribute: DynamoDB.AttributeValue) throws -> Bool { guard case .null = attribute else { return false } return true } func unbox(_ attribute: DynamoDB.AttributeValue, as type: Bool.Type) throws -> Bool { guard case .bool(let value) = attribute else { throw DecodingError.typeMismatch(Bool.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return value } func unbox(_ attribute: DynamoDB.AttributeValue, as type: String.Type) throws -> String { guard case .s(let value) = attribute else { throw DecodingError.typeMismatch(String.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return value } func unbox(_ attribute: DynamoDB.AttributeValue, as type: Double.Type) throws -> Double { guard case .n(let value) = attribute, let unboxResult = Double(value) else { throw DecodingError.typeMismatch(Double.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: Float.Type) throws -> Float { guard case .n(let value) = attribute, let unboxResult = Float(value) else { throw DecodingError.typeMismatch(Float.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: Int.Type) throws -> Int { guard case .n(let value) = attribute, let unboxResult = Int(value) else { throw DecodingError.typeMismatch(Int.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: Int8.Type) throws -> Int8 { guard case .n(let value) = attribute, let unboxResult = Int8(value) else { throw DecodingError.typeMismatch(Int8.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: Int16.Type) throws -> Int16 { guard case .n(let value) = attribute, let unboxResult = Int16(value) else { throw DecodingError.typeMismatch(Int16.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: Int32.Type) throws -> Int32 { guard case .n(let value) = attribute, let unboxResult = Int32(value) else { throw DecodingError.typeMismatch(Int32.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: Int64.Type) throws -> Int64 { guard case .n(let value) = attribute, let unboxResult = Int64(value) else { throw DecodingError.typeMismatch(Int64.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: UInt.Type) throws -> UInt { guard case .n(let value) = attribute, let unboxResult = UInt(value) else { throw DecodingError.typeMismatch(UInt.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: UInt8.Type) throws -> UInt8 { guard case .n(let value) = attribute, let unboxResult = UInt8(value) else { throw DecodingError.typeMismatch(UInt8.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: UInt16.Type) throws -> UInt16 { guard case .n(let value) = attribute, let unboxResult = UInt16(value) else { throw DecodingError.typeMismatch(UInt16.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: UInt32.Type) throws -> UInt32 { guard case .n(let value) = attribute, let unboxResult = UInt32(value) else { throw DecodingError.typeMismatch(UInt32.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: UInt64.Type) throws -> UInt64 { guard case .n(let value) = attribute, let unboxResult = UInt64(value) else { throw DecodingError.typeMismatch(UInt64.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return unboxResult } func unbox(_ attribute: DynamoDB.AttributeValue, as type: Data.Type) throws -> Data { guard case .b(let value) = attribute else { throw DecodingError.typeMismatch(Data.self, .init(codingPath: self.codingPath, debugDescription: "Cannot convert from \(attribute)")) } return value } func unbox<T>(_ attribute: DynamoDB.AttributeValue, as type: T.Type) throws -> T where T: Decodable { return try self.unbox_(attribute, as: T.self) as! T } func unbox_(_ attribute: DynamoDB.AttributeValue, as type: Decodable.Type) throws -> Any { if type == Data.self { return try self.unbox(attribute, as: Data.self) } else { self.storage.pushAttribute(attribute) defer { self.storage.popAttribute() } return try type.init(from: self) } } }
apache-2.0
6dbb25ec3d118576ab76a4bec56d023a
41.230171
197
0.62013
4.7916
false
false
false
false
devincoughlin/swift
test/Parse/foreach.swift
1
1509
// RUN: %target-typecheck-verify-swift struct IntRange<Int> : Sequence, IteratorProtocol { typealias Element = (Int, Int) func next() -> (Int, Int)? {} typealias Iterator = IntRange<Int> func makeIterator() -> IntRange<Int> { return self } } func for_each(r: Range<Int>, iir: IntRange<Int>) { // expected-note {{'r' declared here}} var sum = 0 // Simple foreach loop, using the variable in the body for i in r { sum = sum + i } // Check scoping of variable introduced with foreach loop i = 0 // expected-error{{use of unresolved identifier 'i'; did you mean 'r'?}} // For-each loops with two variables and varying degrees of typedness for (i, j) in iir { sum = sum + i + j } for (i, j) in iir { sum = sum + i + j } for (i, j) : (Int, Int) in iir { sum = sum + i + j } // Parse errors // FIXME: Bad diagnostics; should be just 'expected 'in' after for-each patter'. for i r { // expected-error {{found an unexpected second identifier in constant declaration}} } // expected-note @-1 {{join the identifiers together}} // expected-note @-2 {{join the identifiers together with camel-case}} // expected-error @-3 {{expected 'in' after for-each pattern}} // expected-error @-4 {{expected Sequence expression for for-each loop}} // expected-error @-5 {{variable 'i' is not bound by any pattern}} for i in r sum = sum + i; // expected-error{{expected '{' to start the body of for-each loop}} }
apache-2.0
6529dd91aed8040fabde8506c2d9e425
35.804878
96
0.626243
3.716749
false
false
false
false
atrick/swift
test/expr/closure/trailing.swift
1
28218
// RUN: %target-typecheck-verify-swift -swift-version 4 @discardableResult func takeFunc(_ f: (Int) -> Int) -> Int {} func takeValueAndFunc(_ value: Int, _ f: (Int) -> Int) {} func takeTwoFuncs(_ f: (Int) -> Int, _ g: (Int) -> Int) {} func takeFuncWithDefault(f : ((Int) -> Int)? = nil) {} func takeTwoFuncsWithDefaults(f1 : ((Int) -> Int)? = nil, f2 : ((String) -> String)? = nil) {} // expected-note@-1{{'takeTwoFuncsWithDefaults(f1:f2:)' declared here}} struct X { func takeFunc(_ f: (Int) -> Int) {} func takeValueAndFunc(_ value: Int, f: (Int) -> Int) {} func takeTwoFuncs(_ f: (Int) -> Int, g: (Int) -> Int) {} } func addToMemberCalls(_ x: X) { x.takeFunc() { x in x } x.takeFunc() { $0 } x.takeValueAndFunc(1) { x in x } x.takeTwoFuncs({ x in x }) { y in y } } func addToCalls() { takeFunc() { x in x } takeFunc() { $0 } takeValueAndFunc(1) { x in x } takeTwoFuncs({ x in x }) { y in y } } func makeCalls() { takeFunc { x in x } takeFunc { $0 } takeTwoFuncs ({ x in x }) { y in y } } func notPostfix() { _ = 1 + takeFunc { $0 } } func notLiterals() { struct SR3671 { // <https://bugs.swift.org/browse/SR-3671> var v: Int = 1 { // expected-error {{variable with getter/setter cannot have an initial value}} get { return self.v } } } var x: Int? = nil { get { } } // expected-error {{variable with getter/setter cannot have an initial value}} _ = 1 {} // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{9-9=do }} _ = "hello" {} // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{15-15=do }} _ = [42] {} // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{12-12=do }} _ = (6765, 10946, 17711) {} // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{closure expression is unused}} expected-note@-2 {{did you mean to use a 'do' statement?}} {{28-28=do }} } class C { func map(_ x: (Int) -> Int) -> C { return self } func filter(_ x: (Int) -> Bool) -> C { return self } } var a = C().map {$0 + 1}.filter {$0 % 3 == 0} var b = C().map {$0 + 1} .filter {$0 % 3 == 0} var c = C().map { $0 + 1 } var c2 = C().map // expected-note{{callee is here}} { // expected-warning{{braces here form a trailing closure separated from its callee by multiple newlines}} $0 + 1 } var c3 = C().map // expected-note{{callee is here}} // blah blah blah { // expected-warning{{braces here form a trailing closure separated from its callee by multiple newlines}} $0 + 1 } // Calls with multiple trailing closures should be rejected until we have time // to design it right. // <rdar://problem/16835718> Ban multiple trailing closures func multiTrailingClosure(_ a : () -> (), b : () -> ()) { // expected-note {{'multiTrailingClosure(_:b:)' declared here}} multiTrailingClosure({}) {} // ok multiTrailingClosure {} {} // expected-error {{missing argument for parameter 'b' in call}} expected-error {{consecutive statements on a line must be separated by ';'}} {{26-26=;}} expected-error {{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{27-27=do }} } func labeledArgumentAndTrailingClosure() { // Trailing closures can bind to labeled parameters. takeFuncWithDefault { $0 + 1 } takeFuncWithDefault() { $0 + 1 } // ... but not non-trailing closures. takeFuncWithDefault({ $0 + 1 }) // expected-error {{missing argument label 'f:' in call}} {{23-23=f: }} takeFuncWithDefault(f: { $0 + 1 }) // Trailing closure binds to first parameter... unless only the second matches. takeTwoFuncsWithDefaults { "Hello, " + $0 } // expected-warning{{backward matching of the unlabeled trailing closure is deprecated; label the argument with 'f2' to suppress this warning}} takeTwoFuncsWithDefaults { $0 + 1 } takeTwoFuncsWithDefaults(f1: {$0 + 1 }) } // rdar://problem/17965209 func rdar17965209_f<T>(_ t: T) {} func rdar17965209(x: Int = 0, _ handler: (_ y: Int) -> ()) {} func rdar17965209_test() { rdar17965209() { (y) -> () in rdar17965209_f(1) } rdar17965209(x: 5) { (y) -> () in rdar17965209_f(1) } } // <rdar://problem/22298549> QoI: Unwanted trailing closure produces weird error func limitXY(_ xy:Int, toGamut gamut: [Int]) {} let someInt = 0 let intArray = [someInt] limitXY(someInt, toGamut: intArray) {} // expected-error{{extra trailing closure passed in call}} // <rdar://problem/23036383> QoI: Invalid trailing closures in stmt-conditions produce lowsy diagnostics func retBool(x: () -> Int) -> Bool {} func maybeInt(_: () -> Int) -> Int? {} func twoClosureArgs(_:()->Void, _:()->Void) -> Bool {} class Foo23036383 { init() {} func map(_: (Int) -> Int) -> Int? {} func meth1(x: Int, _: () -> Int) -> Bool {} func meth2(_: Int, y: () -> Int) -> Bool {} func filter(by: (Int) -> Bool) -> [Int] {} } enum MyErr : Error { case A } func r23036383(foo: Foo23036383?, obj: Foo23036383) { if retBool(x: { 1 }) { } // OK if (retBool { 1 }) { } // OK if retBool{ 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{13-13=(x: }} {{18-18=)}} } if retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{13-14=(x: }} {{19-19=)}} } if retBool() { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{14-16=x: }} {{21-21=)}} } else if retBool( ) { 0 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{21-24=x: }} {{29-29=)}} } if let _ = maybeInt { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{28-28=)}} } if let _ = maybeInt { 1 } , true { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{28-28=)}} } if let _ = foo?.map {$0+1} { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{29-29=)}} } if let _ = foo?.map() {$0+1} { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{23-25=}} {{31-31=)}} } if let _ = foo, retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{26-27=(x: }} {{32-32=)}} } if obj.meth1(x: 1) { 0 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{20-22=, }} {{27-27=)}} } if obj.meth2(1) { 0 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{17-19=, y: }} {{24-24=)}} } for _ in obj.filter {$0 > 4} { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(by: }} {{31-31=)}} } for _ in obj.filter {$0 > 4} where true { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(by: }} {{31-31=)}} } for _ in [1,2] where retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{31-32=(x: }} {{37-37=)}} } while retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{16-17=(x: }} {{22-22=)}} } while let _ = foo, retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{29-30=(x: }} {{35-35=)}} } switch retBool { return 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{17-18=(x: }} {{30-30=)}} default: break } do { throw MyErr.A; } catch MyErr.A where retBool { 1 } { // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{32-33=(x: }} {{38-38=)}} } catch { } if let _ = maybeInt { 1 }, retBool { 1 } { } // expected-warning@-1 {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{28-28=)}} // expected-warning@-2 {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{37-38=(x: }} {{43-43=)}} if let _ = foo?.map {$0+1}.map {$0+1} {} // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{33-34=(}} {{40-40=)}} // expected-warning@-1 {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{29-29=)}} if let _ = foo?.map {$0+1}.map({$0+1}) {} // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{29-29=)}} if let _ = foo?.map {$0+1}.map({$0+1}).map{$0+1} {} // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{45-45=(}} {{51-51=)}} // expected-warning@-1 {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{22-23=(}} {{29-29=)}} if twoClosureArgs({}) {} {} // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} {{23-25=, }} {{27-27=)}} if let _ = (foo?.map {$0+1}.map({$0+1}).map{$0+1}) {} // OK if let _ = (foo?.map {$0+1}.map({$0+1})).map({$0+1}) {} // OK } func id<T>(fn: () -> T) -> T { return fn() } func any<T>(fn: () -> T) -> Any { return fn() } func testSR8736() { if !id { true } { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if id { true } == true { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if true == id { true } { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if id { true } ? true : false { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if true ? id { true } : false { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if true ? true : id { false } { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if id { [false,true] }[0] { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if id { { true } } () { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if any { true } as! Bool { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if let _ = any { "test" } as? Int { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if any { "test" } is Int { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if let _ = id { [] as [Int]? }?.first { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if id { true as Bool? }! { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if case id { 1 } = 1 { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if case 1 = id { 1 } { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if case 1 = id { 1 } /*comment*/ { return } // expected-warning {{trailing closure in this context is confusable with the body of the statement; pass as a parenthesized argument to silence this warning}} if case (id { 1 }) = 1 { return } // OK if case 1 = (id { 1 }) { return } // OK if [id { true }].count == 0 { return } // OK if [id { true } : "test"].keys.count == 0 { return } // OK if "\(id { true })" == "foo" { return } // OK if (id { true }) { return } // OK if (id { true }) { } [1, 2, 3].count // expected-warning {{expression of type 'Int' is unused}} if true { } () // OK if true { } () // OK } func overloadOnLabel(a: () -> Void) {} func overloadOnLabel(b: () -> Void) {} func overloadOnLabel(c: () -> Void) {} func overloadOnLabel2(a: () -> Void) {} func overloadOnLabel2(_: () -> Void) {} func overloadOnLabelArgs(_: Int, a: () -> Void) {} func overloadOnLabelArgs(_: Int, b: () -> Void) {} func overloadOnLabelArgs2(_: Int, a: () -> Void) {} func overloadOnLabelArgs2(_: Int, _: () -> Void) {} func overloadOnLabelDefaultArgs(x: Int = 0, a: () -> Void) {} func overloadOnLabelDefaultArgs(x: Int = 1, b: () -> Void) {} func overloadOnLabelSomeDefaultArgs(_: Int, x: Int = 0, a: () -> Void) {} func overloadOnLabelSomeDefaultArgs(_: Int, x: Int = 1, b: () -> Void) {} func overloadOnDefaultArgsOnly(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnDefaultArgsOnly(y: Int = 1, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnDefaultArgsOnly2(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnDefaultArgsOnly2(y: Bool = true, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnDefaultArgsOnly3(x: Int = 0, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnDefaultArgsOnly3(x: Bool = true, a: () -> Void) {} // expected-note 2 {{found this candidate}} func overloadOnSomeDefaultArgsOnly(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}} func overloadOnSomeDefaultArgsOnly(_: Int, y: Int = 1, a: () -> Void) {} // expected-note {{found this candidate}} func overloadOnSomeDefaultArgsOnly2(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}} func overloadOnSomeDefaultArgsOnly2(_: Int, y: Bool = true, a: () -> Void) {} // expected-note {{found this candidate}} func overloadOnSomeDefaultArgsOnly3(_: Int, x: Int = 0, a: () -> Void) {} // expected-note {{found this candidate}} func overloadOnSomeDefaultArgsOnly3(_: Int, x: Bool = true, a: () -> Void) {} // expected-note {{found this candidate}} func testOverloadAmbiguity() { overloadOnLabel {} // expected-error {{ambiguous use of 'overloadOnLabel'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(a:)'}} {{18-19=(a: }} {{21-21=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(b:)'}} {{18-19=(b: }} {{21-21=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(c:)'}} {{18-19=(c: }} {{21-21=)}} overloadOnLabel() {} // expected-error {{ambiguous use of 'overloadOnLabel'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(a:)'}} {{19-21=a: }} {{23-23=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(b:)'}} {{19-21=b: }} {{23-23=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel(c:)'}} {{19-21=c: }} {{23-23=)}} overloadOnLabel2 {} // expected-error {{ambiguous use of 'overloadOnLabel2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel2(a:)'}} {{19-20=(a: }} {{22-22=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabel2'}} {{19-20=(}} {{22-22=)}} overloadOnLabel2() {} // expected-error {{ambiguous use of 'overloadOnLabel2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabel2(a:)'}} {{20-22=a: }} {{24-24=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabel2'}} {{20-22=}} {{24-24=)}} overloadOnLabelArgs(1) {} // expected-error {{ambiguous use of 'overloadOnLabelArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs(_:a:)'}} {{24-26=, a: }} {{28-28=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs(_:b:)'}} {{24-26=, b: }} {{28-28=)}} overloadOnLabelArgs2(1) {} // expected-error {{ambiguous use of 'overloadOnLabelArgs2'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelArgs2(_:a:)'}} {{25-27=, a: }} {{29-29=)}} expected-note {{avoid using a trailing closure to call 'overloadOnLabelArgs2'}} {{25-27=, }} {{29-29=)}} overloadOnLabelDefaultArgs {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{29-30=(a: }} {{32-32=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{29-30=(b: }} {{32-32=)}} overloadOnLabelDefaultArgs() {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{30-32=a: }} {{34-34=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{30-32=b: }} {{34-34=)}} overloadOnLabelDefaultArgs(x: 2) {} // expected-error {{ambiguous use of 'overloadOnLabelDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:a:)'}} {{34-36=, a: }} {{38-38=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelDefaultArgs(x:b:)'}} {{34-36=, b: }} {{38-38=)}} overloadOnLabelSomeDefaultArgs(1) {} // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{35-37=, a: }} {{39-39=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{35-37=, b: }} {{39-39=)}} overloadOnLabelSomeDefaultArgs(1, x: 2) {} // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{41-43=, a: }} {{45-45=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{41-43=, b: }} {{45-45=)}} overloadOnLabelSomeDefaultArgs( // expected-error {{ambiguous use of 'overloadOnLabelSomeDefaultArgs'}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:a:)'}} {{12-5=, a: }} {{4-4=)}} expected-note {{use an explicit argument label instead of a trailing closure to call 'overloadOnLabelSomeDefaultArgs(_:x:b:)'}} {{12-5=, b: }} {{4-4=)}} 1, x: 2 ) { // some } overloadOnDefaultArgsOnly {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly'}} overloadOnDefaultArgsOnly() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly'}} overloadOnDefaultArgsOnly2 {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly2'}} overloadOnDefaultArgsOnly2() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly2'}} overloadOnDefaultArgsOnly3 {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly3(x:a:)'}} overloadOnDefaultArgsOnly3() {} // expected-error {{ambiguous use of 'overloadOnDefaultArgsOnly3(x:a:)'}} overloadOnSomeDefaultArgsOnly(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly'}} overloadOnSomeDefaultArgsOnly2(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly2'}} overloadOnSomeDefaultArgsOnly3(1) {} // expected-error {{ambiguous use of 'overloadOnSomeDefaultArgsOnly3(_:x:a:)'}} } func overloadMismatch(a: () -> Void) -> Bool { return true} func overloadMismatch(x: Int = 0, a: () -> Void) -> Int { return 0 } func overloadMismatchLabel(a: () -> Void) -> Bool { return true} func overloadMismatchLabel(x: Int = 0, b: () -> Void) -> Int { return 0 } func overloadMismatchArgs(_: Int, a: () -> Void) -> Bool { return true} func overloadMismatchArgs(_: Int, x: Int = 0, a: () -> Void) -> Int { return 0 } func overloadMismatchArgsLabel(_: Int, a: () -> Void) -> Bool { return true} func overloadMismatchArgsLabel(_: Int, x: Int = 0, b: () -> Void) -> Int { return 0 } func overloadMismatchMultiArgs(_: Int, a: () -> Void) -> Bool { return true} func overloadMismatchMultiArgs(_: Int, x: Int = 0, y: Int = 1, a: () -> Void) -> Int { return 0 } func overloadMismatchMultiArgsLabel(_: Int, a: () -> Void) -> Bool { return true} func overloadMismatchMultiArgsLabel(_: Int, x: Int = 0, y: Int = 1, b: () -> Void) -> Int { return 0 } func overloadMismatchMultiArgs2(_: Int, z: Int = 0, a: () -> Void) -> Bool { return true} func overloadMismatchMultiArgs2(_: Int, x: Int = 0, y: Int = 1, a: () -> Void) -> Int { return 0 } func overloadMismatchMultiArgs2Label(_: Int, z: Int = 0, a: () -> Void) -> Bool { return true} func overloadMismatchMultiArgs2Label(_: Int, x: Int = 0, y: Int = 1, b: () -> Void) -> Int { return 0 } func testOverloadDefaultArgs() { let a = overloadMismatch {} _ = a as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let b = overloadMismatch() {} _ = b as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let c = overloadMismatchLabel {} _ = c as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let d = overloadMismatchLabel() {} _ = d as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let e = overloadMismatchArgs(0) {} _ = e as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let f = overloadMismatchArgsLabel(0) {} _ = f as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let g = overloadMismatchMultiArgs(0) {} _ = g as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let h = overloadMismatchMultiArgsLabel(0) {} _ = h as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let i = overloadMismatchMultiArgs2(0) {} _ = i as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let j = overloadMismatchMultiArgs2Label(0) {} _ = j as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} } func variadic(_: (() -> Void)...) {} func variadicLabel(closures: (() -> Void)...) {} func variadicOverloadMismatch(_: (() -> Void)...) -> Bool { return true } func variadicOverloadMismatch(x: Int = 0, _: (() -> Void)...) -> Int { return 0 } func variadicOverloadMismatchLabel(a: (() -> Void)...) -> Bool { return true } func variadicOverloadMismatchLabel(x: Int = 0, b: (() -> Void)...) -> Int { return 0 } func variadicAndNonOverload(_: (() -> Void)) -> Bool { return false } func variadicAndNonOverload(_: (() -> Void)...) -> Int { return 0 } func variadicAndNonOverloadLabel(a: (() -> Void)) -> Bool { return false } func variadicAndNonOverloadLabel(b: (() -> Void)...) -> Int { return 0 } func testVariadic() { variadic {} variadic() {} variadic({}) {} variadicLabel {} variadicLabel() {} variadicLabel(closures: {}) {} let a1 = variadicOverloadMismatch {} _ = a1 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let a2 = variadicOverloadMismatch() {} _ = a2 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let b1 = variadicOverloadMismatchLabel {} _ = b1 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let b2 = variadicOverloadMismatchLabel() {} _ = b2 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let c1 = variadicAndNonOverloadLabel {} _ = c1 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} let c2 = variadicAndNonOverload {} _ = c2 as String // expected-error {{cannot convert value of type 'Bool' to type 'String'}} } // rdar://18426302 class TrailingBase { init(fn: () -> ()) {} init(x: Int, fn: () -> ()) {} convenience init() { self.init {} } convenience init(x: Int) { self.init(x: x) {} } } class TrailingDerived : TrailingBase { init(foo: ()) { super.init {} } init(x: Int, foo: ()) { super.init(x: x) {} } } // rdar://85343171 - Spurious warning on trailing closure in argument list. func rdar85343171() { func foo(_ i: Int) -> Bool { true } func bar(_ fn: () -> Void) -> Int { 0 } // Okay, as trailing closure is nested in argument list. if foo(bar {}) {} } // rdar://92521618 - Spurious warning on trailing closure nested within a // closure initializer. func rdar92521618() { func foo(_ fn: () -> Void) -> Int? { 0 } if let _ = { foo {} }() {} guard let _ = { foo {} }() else { return } }
apache-2.0
c60be13af421ed3d1d79f0cd209e2ccc
56.942505
485
0.667163
3.970452
false
false
false
false
qingtianbuyu/Mono
Moon/Classes/Main/View/DiscoverView/MNDiscoverSquareView.swift
1
1603
// // MNDiscoverSquareView.swift // Moon // // Created by YKing on 16/6/11. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNDiscoverSquareView: UIView { @IBOutlet weak var squareView: UICollectionView! var mod: MNModEntity? { didSet { self.squareView.reloadData() } } override func awakeFromNib() { super.awakeFromNib() let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: (ScreenWidth - 1) * 0.5, height: 227) layout.minimumLineSpacing = 1 layout.minimumInteritemSpacing = 1 self.squareView.collectionViewLayout = layout self.squareView.backgroundColor = commonBgColor self.squareView.delegate = self self.squareView.dataSource = self self.squareView.bounces = false let nib = UINib(nibName: String(describing: MNDiscoverSquareCell.self), bundle: nil) self.squareView.register(nib, forCellWithReuseIdentifier: MNDiscoverSquareCell.viewIdentify) } } extension MNDiscoverSquareView: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return mod?.entity_list?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = squareView.dequeueReusableCell(withReuseIdentifier: MNDiscoverSquareCell.viewIdentify, for: indexPath) as! MNDiscoverSquareCell let mode = mod?.entity_list![(indexPath as NSIndexPath).row] cell.mode = mode return cell } }
mit
2022aa491ad81ccee0a1e4e901044e82
30.372549
142
0.738125
4.819277
false
false
false
false
sora0077/iTunesMusic
Sources/Model/Protocol/Fetchable.swift
1
4683
// // Fetchable.swift // iTunesMusic // // Created by 林達也 on 2016/08/06. // Copyright © 2016年 jp.sora0077. All rights reserved. // import Foundation import RxSwift import Timepiece import ErrorEventHandler // MARK: - Fetchable public protocol Fetchable: class { var requestState: Observable<RequestState> { get } func fetch(ifError errorType: ErrorLog.Error.Type, level: ErrorLog.Level) func refresh(ifError errorType: ErrorLog.Error.Type, level: ErrorLog.Level) func refresh(force: Bool, ifError errorType: ErrorLog.Error.Type, level: ErrorLog.Level) } private struct FetchableKey { static var requestState: UInt8 = 0 } extension Fetchable { public var requestState: Observable<RequestState> { // swiftlint:disable:next force_cast return associatedObject(self, &FetchableKey.requestState, initial: asObservable((self as! _Fetchable)._requestState).distinctUntilChanged()) } public func fetch(ifError errorType: ErrorLog.Error.Type, level: ErrorLog.Level) { fetch(ifError: errorType, level: level, completion: { _ in }) } func fetch(ifError errorType: ErrorLog.Error.Type, level: ErrorLog.Level, completion: @escaping (Swift.Error?) -> Void) { guard doOnMainThread(execute: self.fetch(ifError: errorType, level: level, completion: completion)) else { return } _request(refreshing: false, force: false, ifError: errorType, level: level, completion: completion) } public func refresh(ifError errorType: ErrorLog.Error.Type, level: ErrorLog.Level) { refresh(force: false, ifError: errorType, level: level) } public func refresh(force: Bool, ifError errorType: ErrorLog.Error.Type, level: ErrorLog.Level) { guard doOnMainThread(execute: self.refresh(force: force, ifError: errorType, level: level)) else { return } // swiftlint:disable:next force_cast let `self` = self as! _Fetchable if force || self._needRefresh { _request(refreshing: true, force: force, ifError: errorType, level: level) } } private func _request(refreshing: Bool, force: Bool, ifError errorType: ErrorLog.Error.Type, level: ErrorLog.Level, completion: @escaping (Swift.Error?) -> Void = { _ in }) { // swiftlint:disable:next force_cast let `self` = self as! _Fetchable if [.done, .requesting].contains(self._requestState.value) { return } print("now request, \(self)") self._requesting.value = true self._refreshing.value = refreshing self._requestState.value = .requesting self.request(refreshing: refreshing, force: force, ifError: errorType, level: level) { [weak self] requestState in DispatchQueue.main.async { self?._requesting.value = false self?._refreshing.value = false self?._requestState.value = requestState if case .error(let error) = requestState { ErrorLog.enqueue(error: error, with: errorType, level: level) completion(error) } else { completion(nil) } tick() } } } } // MARK: - _Fetchable protocol _Fetchable: class, Fetchable { var _refreshing: Variable<Bool> { get } var _requesting: Variable<Bool> { get } var _requestState: Variable<RequestState> { get } var _refreshAt: Date { get } var _refreshDuration: Duration { get } var _needRefresh: Bool { get } var _hasNoPaginatedContents: Bool { get } func request(refreshing: Bool, force: Bool, ifError errorType: ErrorLog.Error.Type, level: ErrorLog.Level, completion: @escaping (RequestState) -> Void) } private struct _FetchableKey { static var _refreshing: UInt8 = 0 static var _requesting: UInt8 = 0 static var _requestState: UInt8 = 0 } extension _Fetchable { var _needRefresh: Bool { return Date() - _refreshAt > _refreshDuration } var _refreshing: Variable<Bool> { return associatedObject(self, &_FetchableKey._refreshing, initial: Variable(false)) } var _requesting: Variable<Bool> { return associatedObject(self, &_FetchableKey._requesting, initial: Variable(false)) } var _requestState: Variable<RequestState> { return associatedObject(self, &_FetchableKey._requestState, initial: Variable(.none)) } var _hasNoPaginatedContents: Bool { switch _requestState.value { case .error, .done: return true default: return false } } }
mit
edcb1bb5bf5f488e9071e0d21896c450
31.915493
178
0.64356
4.464183
false
false
false
false
silence0201/Swift-Study
SwiftLearn/MySwift04_optional.playground/Contents.swift
1
5088
//: Playground - noun: a place where people can play import UIKit // 可选型 // 操作灵活 大量使用 // 概念 使用方法 // var eCode: Int = 404 //eCode = nil //UICOlor color = nil // nil是一种特殊的类型, 代表没有. 不可以直接赋值给其他任何类型变量. var eCode2: Int? = nil // 声明errorCode2是整型可选型. var color: UIColor? = nil // 声明errorCode2是UIColor可选型. let imInt = 405 eCode2 = imInt // imInt = errorCode2 //报错. print(eCode2!) let imOptional: String? = nil var errorCode: String? = "404" print(errorCode as Any) //可选型是不直接使用的, 这也是Swift是一门安全的语言. // 如果要使用须要解包, 变量后加!号强制解包, 但是是有风险的, 因为你不知道变量是否是nil空. //"The errorCode is " + errorCode "The errorCode is " + errorCode! if errorCode != nil{ "The errorCode is " + errorCode! } else { "No error" } //我们尝试把errorCode解包并赋值给errorCode变量, 解包后即是非空的值, 且也不是可选型. if let errorCode = errorCode{ //errorCode解包后只在{ }中有效使用 "The errorCode is " + errorCode } else{ "No error" //说明可选型errorCode为nil } var errorMessage:String? = "Not found" // 一次解包多个可选型变量 if let errorCode = errorCode, let errorMessage = errorMessage { "The errorCode is " + errorCode + "\n The errorMessage is " + errorMessage } // 一次解包多个可选型变量 并 限定errorCode 等于 "404"的情况. if let errorCode = errorCode, let errorMessage = errorMessage , errorCode == "404"{ "The errorCode is " + errorCode + "\n The errorMessage is " + errorMessage } //可选型解包使用. if let errorMessage = errorMessage{ errorMessage.uppercased() } //功能同上, 虽然errorMessage是可选型, 尝试去解包并UpperCase, 如果是nil则什么也不做, 返回nil. errorMessage?.uppercased() errorMessage!.uppercased() //强制解包并UpperCase, 但是当errorMessage强制解包失败, 则报错. //因为errorMessage可能尝试解包失败. 若失败则nil, 为了能够存住这个nil, 所以upperCaseErrorMessage也是可选型. var upperCaseErrorMessage = errorMessage?.uppercased() if let errorMessage = errorMessage?.uppercased(){ //可选型解包upppercase使用. errorMessage //"NOT FOUND" } //可选型解包使用3个实例. var message: String if let errorMessage = errorMessage{ message = errorMessage } else{ message = "No error" } message = errorMessage == nil ? "No error" : errorMessage! message = errorMessage ?? "No error" /*** * 可选型在元组中的使用 ***/ var error1: (errorCode: Int, errorMessage: String?) = (404, "Not found") //设置元组的errorMessage分量是可选型. error1.errorMessage = nil error1 //可选型元组变量. var error2: (errorCode:Int, errorMessage: String)? = (404, "Not found") error2 = nil //可选型元组合变量, 且分量errorMessage也是可选型. 这样说明那些是可以为空nil var error3: (errorCode:Int, errorMessage:String?)? = (404, "Not found") //可选型实际应用. var ageInput:String = "zx" var age = Int(ageInput) //转换输入的"16"字符串. print(age ?? "nil") if let age = Int(ageInput) , age < 20{ print("You're a teenager") } var greetings = "Hello" var range1 = greetings.range(of: "ll") //返回一个前闭后开的区间Range<Index>?类型. var range2 = greetings.range(of: "oo") //隐式可选型, eMsg可以存放nil, // 使用的时候可以直接使用, 一旦为空, 就会报错, 这是危险的. 我们也可以对隐式的可选型进行解包, 但它就失去了可选型的意义了. // 隐式可选型基本上完全用于: 当我们定义一个类时, 对类中的某些变量, 可能用隐式可选型, 这样当类刚创建时, 这个变量可以是nil // 但是当用户真正使用这个变量时, 要保证这个类变量有值. var eMsg:String! = nil //隐式可选型声明用! eMsg = "Not found" "The message is " + eMsg // 隐式可选型可直接使用. //隐式可选型在类中实际应用. class City{ let cityName: String unowned var country : Country //unowned必免内存泄漏. init(cityName:String, country: Country){ self.cityName = cityName self.country = country } } //由于在Country的构造函数中初始化成员capitalCity成员时, City构造时必需要country实例self, // 但是此时Country实例还未构建完成, 此时若capital为可选型时, 就允许其暂时为空nil, 继续完成Country的初始化. class Country{ let countryName: String var capitalCity: City! //隐式可选型. init(countryName: String, capitalCity: String){ self.countryName = countryName self.capitalCity = City(cityName: capitalCity, country: self) } func showInfo(){ print("This is \(countryName).") print("The capital is \(capitalCity.cityName).") } } let china = Country(countryName: "china", capitalCity: "BeiJing") china.showInfo()
mit
35e77c394fb24e736b30ad28ac6e452a
20.092896
99
0.698446
3.001555
false
false
false
false
jonatascb/Smashtag
Smashtag/Twitter/User.swift
1
2048
// // User.swift // Twitter // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import Foundation // container to hold data about a Twitter user public struct User: Printable { public var screenName: String public var name: String public var profileImageURL: NSURL? public var verified: Bool = false public var id: String! public var description: String { var v = verified ? " ✅" : ""; return "@\(screenName) (\(name))\(v)" } // MARK: - Private Implementation init?(data: NSDictionary?) { let name = data?.valueForKeyPath(TwitterKey.Name) as? String let screenName = data?.valueForKeyPath(TwitterKey.ScreenName) as? String if name != nil && screenName != nil { self.name = name! self.screenName = screenName! self.id = data?.valueForKeyPath(TwitterKey.ID) as? String if let verified = data?.valueForKeyPath(TwitterKey.Verified)?.boolValue { self.verified = verified } if let urlString = data?.valueForKeyPath(TwitterKey.ProfileImageURL) as? String { self.profileImageURL = NSURL(string: urlString) } } else { return nil } } var asPropertyList: AnyObject { var dictionary = Dictionary<String,String>() dictionary[TwitterKey.Name] = self.name dictionary[TwitterKey.ScreenName] = self.screenName dictionary[TwitterKey.ID] = self.id dictionary[TwitterKey.Verified] = verified ? "YES" : "NO" dictionary[TwitterKey.ProfileImageURL] = profileImageURL?.absoluteString return dictionary } init() { screenName = "Unknown" name = "Unknown" } struct TwitterKey { static let Name = "name" static let ScreenName = "screen_name" static let ID = "id_str" static let Verified = "verified" static let ProfileImageURL = "profile_image_url" } }
mit
fdf66ab0d80ca5587f9e71fbc03cc6e2
30
106
0.613392
4.671233
false
false
false
false
lightsprint09/socket.io-client-swift
Source/SocketIO/Util/SocketClientManager.swift
1
3372
// // SocketClientManager.swift // Socket.IO-Client-Swift // // Created by Erik Little on 6/11/16. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** Experimental socket manager. API subject to change. Can be used to persist sockets across ViewControllers. Sockets are strongly stored, so be sure to remove them once they are no longer needed. Example usage: ``` let manager = SocketClientManager.sharedManager manager["room1"] = socket1 manager["room2"] = socket2 manager.removeSocket(socket: socket2) manager["room1"]?.emit("hello") ``` */ open class SocketClientManager : NSObject { // MARK: Properties. /// The shared manager. @objc open static let sharedManager = SocketClientManager() private var sockets = [String: SocketIOClient]() /// Gets a socket by its name. /// /// - returns: The socket, if one had the given name. open subscript(string: String) -> SocketIOClient? { get { return sockets[string] } set(socket) { sockets[string] = socket } } // MARK: Methods. /// Adds a socket. /// /// - parameter socket: The socket to add. /// - parameter labeledAs: The label for this socket. @objc open func addSocket(_ socket: SocketIOClient, labeledAs label: String) { sockets[label] = socket } /// Removes a socket by a given name. /// /// - parameter withLabel: The label of the socket to remove. /// - returns: The socket for the given label, if one was present. @objc @discardableResult open func removeSocket(withLabel label: String) -> SocketIOClient? { return sockets.removeValue(forKey: label) } /// Removes a socket. /// /// - parameter socket: The socket to remove. /// - returns: The socket if it was in the manager. @objc @discardableResult open func removeSocket(_ socket: SocketIOClient) -> SocketIOClient? { var returnSocket: SocketIOClient? for (label, dictSocket) in sockets where dictSocket === socket { returnSocket = sockets.removeValue(forKey: label) } return returnSocket } /// Removes all the sockets in the manager. @objc open func removeSockets() { sockets.removeAll() } }
apache-2.0
045b8fc8e2987d460c21f3f2898778d8
29.654545
81
0.674081
4.442688
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAccountPicker/Tests/HeaderViewTests.swift
1
3493
// Copyright © Blockchain Luxembourg S.A. All rights reserved. @testable import FeatureAccountPickerUI import Localization import SnapshotTesting import SwiftUI import UIComponentsKit import XCTest class HeaderViewTests: XCTestCase { override func setUp() { super.setUp() isRecording = false } func testNormal() { let view = HeaderView( viewModel: .normal( title: "Send Crypto Now", subtitle: "Choose a Wallet to send cypto from.", image: ImageAsset.iconSend.image, tableTitle: "Select a Wallet", searchable: false ), searchText: .constant(nil), isSearching: .constant(false) ) .fixedSize() assertSnapshot(matching: view, as: .image) } func testNormalNoImage() { let view = HeaderView( viewModel: .normal( title: "Send Crypto Now", subtitle: "Choose a Wallet to send cypto from.", image: nil, tableTitle: "Select a Wallet", searchable: false ), searchText: .constant(nil), isSearching: .constant(false) ) .fixedSize() assertSnapshot(matching: view, as: .image) } func testNormalNoTableTitle() { let view = HeaderView( viewModel: .normal( title: "Send Crypto Now", subtitle: "Choose a Wallet to send cypto from.", image: ImageAsset.iconSend.image, tableTitle: nil, searchable: false ), searchText: .constant(nil), isSearching: .constant(false) ) .fixedSize() assertSnapshot(matching: view, as: .image) } func testNormalSearch() { let view = HeaderView( viewModel: .normal( title: "Send Crypto Now", subtitle: "Choose a Wallet to send cypto from.", image: ImageAsset.iconSend.image, tableTitle: nil, searchable: true ), searchText: .constant(nil), isSearching: .constant(false) ) .fixedSize() assertSnapshot(matching: view, as: .image) } func testNormalSearchCollapsed() { let view = HeaderView( viewModel: .normal( title: "Send Crypto Now", subtitle: "Choose a Wallet to send cypto from.", image: ImageAsset.iconSend.image, tableTitle: nil, searchable: true ), searchText: .constant("Search"), isSearching: .constant(true) ) .animation(nil) .frame(width: 375) assertSnapshot(matching: view, as: .image) } func testSimple() { let view = HeaderView( viewModel: .simple( subtitle: "Subtitle", searchable: false ), searchText: .constant(nil), isSearching: .constant(false) ) .fixedSize() assertSnapshot(matching: view, as: .image) } func testNone() { let view = HeaderView( viewModel: .none, searchText: .constant(nil), isSearching: .constant(false) ) .fixedSize() assertSnapshot(matching: view, as: .image) } }
lgpl-3.0
ba60814d4563d8a8d3ad85fff6af2c71
26.496063
64
0.517182
5.235382
false
true
false
false
MLSDev/AppRouter
Sources/Core/AppRouter.swift
1
2854
import Foundation import UIKit /// Namespacing class open class AppRouter { /// Provides default AppRouter instance public static var shared = AppRouter() /// Provides application keyWindow. In normal cases returns UIApplication.sharedApplication().delegate?.window if available or creates new one if not. /// If appDelegate does not implement UIApplicationDelegate.window property - returns UIApplication.sharedApplication().keyWindow public static var window: UIWindow { return shared.window } /// Current window which Router work with open var window: UIWindow { return windowProvider() } open var windowProvider: () -> UIWindow public convenience init() { self.init(windowProvider: WindowProvider.dynamic.window) } public init(windowProvider: @escaping () -> UIWindow) { self.windowProvider = windowProvider } /// Defines AppRouter output target public static var debugOutput: (String) -> () = DebugOutput.nsLog.debugOutput internal static func print(_ str: String) { debugOutput(str) } /// Few predefined debugOutput targets public enum DebugOutput { /// hides output case none /// uses Swift.print for output. Can't be seen in Device Console case print /// uses Foundation.NSLog for output. Visible in Device Console case nsLog public func debugOutput(_ str: String) { switch self { case .none: return case .print: return Swift.print(str) case .nsLog: return Foundation.NSLog(str) } } } public enum WindowProvider { case `static`(UIWindow) case dynamic func window() -> UIWindow { switch self { case .static(let window): return window case .dynamic: guard let delegate = UIApplication.shared.delegate else { fatalError("no appDelegate found") } if let windowProperty = delegate.window { if let window = windowProperty { return window } else { let newWindow = UIWindow(frame: UIScreen.main.bounds) delegate.perform(#selector(setter: UIApplicationDelegate.window), with: newWindow) newWindow.makeKeyAndVisible() return newWindow } } else { guard let window = UIApplication.shared.keyWindow else { fatalError("delegate doesn't implement window property and no UIApplication.sharedApplication().keyWindow available") } return window } } } } }
mit
95fb38c87a3ba23ee8a2934feb0ab863
34.234568
196
0.584793
5.730924
false
false
false
false
jeroendesloovere/examples-swift
Swift-Playgrounds/UsingSwiftWithCocoaAndObjective-C/InteractingWithObjective-C-APIs.playground/section-1.swift
1
6769
// Interacting with Objective-C APIs import UIKit //import CoreGraphics //import Foundation // Initialization // UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped]; let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped)! let myTextField = UITextField(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 40.0)) // Objective-C Factory Methods // UIColor *color = [UIColor colorWithRed: 0.5 green:0.0 blue:0.5 alpha:1.0] let color = UIColor(red: 0.5, green: 0.0, blue: 0.5, alpha: 1.0) // Accessing Properties myTextField.textColor = UIColor.darkGrayColor() myTextField.text = "Hello world" if myTextField.editing { //myTextField.editing = false } // In Objective-C, a method that returns a value and takes no arguments can be treated as an implicit getter—and be called using the same syntax as a getter for a property. This is not the case in Swift. In Swift, only properties that are written using the @property syntax in Objective-C are imported as properties. // Working with Methods // When Objective-C methods come over to Swift, // - the first part of an Objective-C selector becomes the base method name and appears outside the parentheses. // - The first argument appears immediately inside the parentheses, without a name. // - The rest of the selector pieces correspond to argument names and go inside the parentheses. // - All selector pieces are required at the call site. let mySubview = UIView() // [myTableView insertSubview:mySubview atIndex:2]; myTableView.insertSubview(mySubview, atIndex: 2) myTableView.layoutIfNeeded() // Parenthesis still required despite lack of arguments // id Compatibility // AnyObject is a protocol type. // The AnyObject protocol allows you to write type-safe Swift code while maintaining the flexibility of an untyped object. Because of the additional safety provided by the AnyObject protocol, Swift imports id as AnyObject. var myObject: AnyObject = UITableViewCell() myObject = NSDate() // You can also call any Objective-C method and access any property without casting to a more specific class type. let futureDate = myObject.dateByAddingTimeInterval let timeSinceNow = myObject.timeIntervalSinceNow // In contrast with Objective-C, if you invoke a method or access a property that does not exist on an AnyObject typed object, it is a runtime error. For example, the following code compiles without complaint and then causes an unrecognized selector error at runtime: // myObject.characterAtIndex(5) // This causes a runtime error // When you call an Objective-C method on an AnyObject type object, the method call actually behaves like an implicitly unwrapped optional. You can use the same optional chaining syntax you would use for optional methods in protocols to optionally invoke a method on AnyObject. //let myLength = myObject.length? //let myChar = myObject.characterAtIndex?(5) /* if let fifthCharacter = myObject.characterAtIndex(5) { println("Found \(fifthCharacter) at index 5") } */ let userDefaults = NSUserDefaults.standardUserDefaults() let lastRefreshDate: AnyObject? = userDefaults.objectForKey("LastRefreshDate") if let date = lastRefreshDate as? NSDate { println("\(date.timeIntervalSinceReferenceDate)") } // The following force unwraps the lastRefreshDate even though it is nil. //let myDate = lastRefreshDate as NSDate //let timeInterval = myDate.timeIntervalSinceReferenceDate // Working with nil // Swift makes all classes in argument types and return types optional in imported Objective-C APIs. // Swift imports object types as implicitly unwrapped optionals. // Extensions extension UIBezierPath { convenience init(triangleSideLength: Float, origin: CGPoint) { self.init() let squareRoot = Float(sqrt(3.0)) let altitude = (squareRoot * triangleSideLength) / 2 moveToPoint(origin) let point1 = CGPoint(x: CGFloat(triangleSideLength), y: origin.x) addLineToPoint(CGPoint(x: CGFloat(triangleSideLength), y: origin.x)) addLineToPoint(CGPoint(x: CGFloat(triangleSideLength / 2), y: CGFloat(altitude))) closePath() } } // ??? A bunch of explicit casting is required above when the docs indicate that they shouldn't be needed. // You can use extensions to add properties (including class and static properties). However, these properties must be computed; extensions can’t add stored properties to classes, structures, or enumerations. extension CGRect { var area: CGFloat { return width * height } } let rect = CGRect(x: 0.0, y: 0.0, width: 10.0, height: 50.0) let area = rect.area // Closures // Objective-C blocks are automatically imported as Swift closures. // void (^completionBlock)(NSData *, NSError *) = ^(NSData *data, NSError *error) { /* ... */ } let completionBlock: (NSData, NSError) -> Void = { data, error in /* ... */ } // Closures have similar capture semantics as blocks but differ in one key way: Variables are mutable rather than copied. In other words, the behavior of __block in Objective-C is the default behavior for variables in Swift. // Object Comparison // Equality (==), compares the contents of the objects. // Identity (===), determines whether or not the constants or variables refer to the same object instance. // Swift invokes the isEqual: method defined on the NSObject class. The NSObject class only performs an identity comparison, so you should implement your own isEqual: method in classes that derive from the NSObject class. // // Swift Type Compatibility // The @objc attribute makes your Swift API available in Objective-C and the Objective-C runtime. @objc(Squirrel) class Белка { @objc(initWithName:) init(имя: String) { /* ... */ } @objc(hideNuts:inTree:) func прячьОрехи(Int, вДереве: Dictionary<String, String>) { /* ... */ } } // Objective-C Selectors // An Objective-C selector is a type that refers to the name of an Objective-C method. In Swift, Objective-C selectors are represented by the Selector structure. // In Swift string literals can be automatically converted to selectors class MyViewController: UIViewController { let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50)) override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) myButton.addTarget(self, action: "tappedButton:", forControlEvents: .TouchUpInside) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tappedButton(sender: UIButton!) { println("tapped button") } }
mit
c538b5e2483fe90b08328a428b52dabe
42.483871
317
0.743175
4.388021
false
false
false
false
xxxAIRINxxx/Cmg
Proj/Demo/SliderTableView.swift
1
2080
// // SliderTableView.swift // Demo // // Created by xxxAIRINxxx on 2016/02/20. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit import Cmg final class SliderTableView: UITableView { var upsdateSliderHandler: (() -> Void)? fileprivate var sliders: [Slider] = [] override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } fileprivate func commonInit() { self.register(UINib(nibName: "SliderCell", bundle: nil), forCellReuseIdentifier: "SliderCell") self.dataSource = self self.delegate = self } func updateSliders(_ filter: PhotoProcessable) { self.sliders = filter.sliders self.reloadData() } } extension SliderTableView: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.sliders.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SliderCell", for: indexPath) as! SliderCell let slider = self.sliders[(indexPath as NSIndexPath).row] cell.label.text = slider.name cell.valueLabel.text = slider.currentValue.description cell.slider.maximumValue = slider.range.maximumValue cell.slider.minimumValue = slider.range.minimumValue cell.slider.value = slider.currentValue cell.upsdateSliderHandler = { [weak self] value in slider.currentValue = value self?.upsdateSliderHandler?() } return cell } } extension SliderTableView: UITableViewDelegate { func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
mit
411234a1ca7ca1c0f91e9dd91e777160
28.28169
109
0.65849
4.834884
false
false
false
false
uasys/swift
test/Constraints/closures.swift
1
21691
// RUN: %target-typecheck-verify-swift -swift-version 3 // RUN: %target-typecheck-verify-swift -swift-version 4 func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {} var intArray : [Int] _ = myMap(intArray, { String($0) }) _ = myMap(intArray, { x -> String in String(x) } ) // Closures with too few parameters. func foo(_ x: (Int, Int) -> Int) {} foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} foo({ [intArray] in $0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} struct X {} func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {} func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {} var strings : [String] _ = mySort(strings, { x, y in x < y }) // Closures with inout arguments. func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U { var t2 = t return f(&t2) } struct X2 { func g() -> Float { return 0 } } _ = f0(X2(), {$0.g()}) // Closures with inout arguments and '__shared' conversions. func inoutToSharedConversions() { func fooOW<T, U>(_ f : (__owned T) -> U) {} fooOW({ (x : Int) in return Int(5) }) // '__owned'-to-'__owned' allowed fooOW({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__owned' allowed fooOW({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(_) -> _'}} func fooIO<T, U>(_ f : (inout T) -> U) {} fooIO({ (x : inout Int) in return Int(5) }) // 'inout'-to-'inout' allowed fooIO({ (x : __shared Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__shared Int) -> Int' to expected argument type '(inout _) -> _'}} fooIO({ (x : Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(inout _) -> _'}} func fooSH<T, U>(_ f : (__shared T) -> U) {} fooSH({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__shared' allowed fooSH({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__shared _) -> _'}} fooSH({ (x : Int) in return Int(5) }) // '__owned'-to-'__shared' allowed } // Autoclosure func f1(f: @autoclosure () -> Int) { } func f2() -> Int { } f1(f: f2) // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}} f1(f: 5) // Ternary in closure var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"} // <rdar://problem/15367882> func foo() { not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}} } // <rdar://problem/15536725> struct X3<T> { init(_: (T) -> ()) {} } func testX3(_ x: Int) { var x = x _ = X3({ x = $0 }) _ = x } // <rdar://problem/13811882> func test13811882() { var _ : (Int) -> (Int, Int) = {($0, $0)} var x = 1 var _ : (Int) -> (Int, Int) = {($0, x)} x = 2 } // <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement // <https://bugs.swift.org/browse/SR-3671> func r21544303() { var inSubcall = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false // This is a problem, but isn't clear what was intended. var somethingElse = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false var v2 : Bool = false v2 = inSubcall { // expected-error {{cannot call value of non-function type 'Bool'}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} } } // <https://bugs.swift.org/browse/SR-3671> func SR3671() { let n = 42 func consume(_ x: Int) {} { consume($0) }(42) ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; // This is technically a valid call, so nothing goes wrong until (42) { $0(3) } { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) }) { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; { $0(3) } { [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) }) { [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; // Equivalent but more obviously unintended. { $0(3) } // expected-note {{callee is here}} { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ({ $0(3) }) // expected-note {{callee is here}} { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ; // Also a valid call (!!) { $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}} consume(111) } // <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure func r22162441(_ lines: [String]) { _ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} _ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} } func testMap() { let a = 42 [1,a].map { $0 + 1.0 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }} } // <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier [].reduce { $0 + $1 } // expected-error {{cannot invoke 'reduce' with an argument list of type '((_, _) -> _)'}} // <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments var _: () -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }} var _: (Int) -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}} var _: (Int) -> Int = { 0 } // expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }} var _: (Int, Int) -> Int = {0} // expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {$0+$1} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}} var _: (Int) -> Int = {a,b in 0} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}} var _: (Int) -> Int = {a,b,c in 0} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {a, b in a+b} // <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument func r15998821() { func take_closure(_ x : (inout Int) -> ()) { } func test1() { take_closure { (a : inout Int) in a = 42 } } func test2() { take_closure { a in a = 42 } } func withPtr(_ body: (inout Int) -> Int) {} func f() { withPtr { p in return p } } let g = { x in x = 3 } take_closure(g) } // <rdar://problem/22602657> better diagnostics for closures w/o "in" clause var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} // Crash when re-typechecking bodies of non-single expression closures struct CC {} func callCC<U>(_ f: (CC) -> U) -> () {} func typeCheckMultiStmtClosureCrash() { callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{11-11= () -> Int in }} _ = $0 return 1 } } // SR-832 - both these should be ok func someFunc(_ foo: ((String) -> String)?, bar: @escaping (String) -> String) { let _: (String) -> String = foo != nil ? foo! : bar let _: (String) -> String = foo ?? bar } func verify_NotAC_to_AC_failure(_ arg: () -> ()) { func takesAC(_ arg: @autoclosure () -> ()) {} takesAC(arg) // expected-error {{function produces expected type '()'; did you mean to call it with '()'?}} } // SR-1069 - Error diagnostic refers to wrong argument class SR1069_W<T> { func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {} } class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() } struct S<T> { let cs: [SR1069_C<T>] = [] func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable { let wrappedMethod = { (object: AnyObject, value: T) in } // expected-error @+1 {{value of optional type 'Object?' not unwrapped; did you mean to use '!' or '?'?}} cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) } } } // Make sure we cannot infer an () argument from an empty parameter list. func acceptNothingToInt (_: () -> Int) {} func testAcceptNothingToInt(ac1: @autoclosure () -> Int) { acceptNothingToInt({ac1($0)}) // expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}} } // <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference) struct Thing { init?() {} } // This throws a compiler error let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> (Thing) }} // Commenting out this makes it compile _ = thing return thing } // <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches func r21675896(file : String) { let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> String in }} if true { return "foo" } else { return file } }().pathExtension } // <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _") func ident<T>(_ t: T) -> T {} var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}} // <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block var afterMessageCount : Int? func uintFunc() -> UInt {} func takeVoidVoidFn(_ a : () -> ()) {} takeVoidVoidFn { () -> Void in afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}} } // <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure func f19997471(_ x: String) {} func f19997471(_ x: Int) {} func someGeneric19997471<T>(_ x: T) { takeVoidVoidFn { f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}} // expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (String), (Int)}} } } // <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r } [0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> Int }} _ in let r = (1,2).0 return r } // <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type func rdar21078316() { var foo : [String : String]? var bar : [(String, String)]? bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) -> [(String, String)]' expects 1 argument, but 2 were used in closure body}} } // <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure var numbers = [1, 2, 3] zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}} // <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type' func foo20868864(_ callback: ([String]) -> ()) { } func rdar20868864(_ s: String) { var s = s foo20868864 { (strings: [String]) in s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}} } } // <rdar://problem/22058555> crash in cs diags in withCString func r22058555() { var firstChar: UInt8 = 0 "abc".withCString { chars in firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}} } } // <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type func r20789423() { class C { func f(_ value: Int) { } } let p: C print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}} let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> String }} print("a") return "hi" } } // Make sure that behavior related to allowing trailing closures to match functions // with Any as a final parameter is the same after the changes made by SR-2505, namely: // that we continue to select function that does _not_ have Any as a final parameter in // presence of other possibilities. protocol SR_2505_Initable { init() } struct SR_2505_II : SR_2505_Initable {} protocol P_SR_2505 { associatedtype T: SR_2505_Initable } extension P_SR_2505 { func test(it o: (T) -> Bool) -> Bool { return o(T.self()) } } class C_SR_2505 : P_SR_2505 { typealias T = SR_2505_II func test(_ o: Any) -> Bool { return false } func call(_ c: C_SR_2505) -> Bool { // Note: no diagnostic about capturing 'self', because this is a // non-escaping closure -- that's how we know we have selected // test(it:) and not test(_) return c.test { o in test(o) } } } let _ = C_SR_2505().call(C_SR_2505()) // <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic extension Collection { func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index { return startIndex } } func fn_r28909024(n: Int) { return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}} _ in true } } // SR-2994: Unexpected ambiguous expression in closure with generics struct S_2994 { var dataOffset: Int } class C_2994<R> { init(arg: (R) -> Void) {} } func f_2994(arg: String) {} func g_2994(arg: Int) -> Double { return 2 } C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}} let _ = { $0[$1] }(1, 1) // expected-error {{cannot subscript a value of incorrect or ambiguous type}} let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}} let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}} // https://bugs.swift.org/browse/SR-403 // The () -> T => () -> () implicit conversion was kicking in anywhere // inside a closure result, not just at the top-level. let mismatchInClosureResultType : (String) -> ((Int) -> Void) = { (String) -> ((Int) -> Void) in return { } // expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} } // SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS func sr3520_1<T>(_ g: (inout T) -> Int) {} sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}} // This test makes sure that having closure with inout argument doesn't crash with member lookup struct S_3520 { var number1: Int } func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {} sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error {{type of expression is ambiguous without more context}} // SR-3073: UnresolvedDotExpr in single expression closure struct SR3073Lense<Whole, Part> { let set: (inout Whole, Part) -> () } struct SR3073 { var number1: Int func lenses() { let _: SR3073Lense<SR3073, Int> = SR3073Lense( set: { $0.number1 = $1 } // ok ) } } // SR-3479: Segmentation fault and other error for closure with inout parameter func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {} func sr3497() { let _ = sr3497_unfold((0, 0)) { s in 0 } // ok } // SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs let _: ((Any?) -> Void) = { (arg: Any!) in } // This example was rejected in 3.0 as well, but accepting it is correct. let _: ((Int?) -> Void) = { (arg: Int!) in } // rdar://30429709 - We should not attempt an implicit conversion from // () -> T to () -> Optional<()>. func returnsArray() -> [Int] { return [] } returnsArray().flatMap { $0 }.flatMap { } // expected-warning@-1 {{expression of type 'Int' is unused}} // expected-warning@-2 {{result of call to 'flatMap' is unused}} // rdar://problem/30271695 _ = ["hi"].flatMap { $0.isEmpty ? nil : $0 } // rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected func r32432145(_ a: () -> ()) {} r32432145 { _,_ in // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}} print("answer is 42") } // rdar://problem/30106822 - Swift ignores type error in closure and presents a bogus error about the caller [1, 2].first { $0.foo = 3 } // expected-error@-1 {{value of type 'Int' has no member 'foo'}} // rdar://problem/32433193, SR-5030 - Higher-order function diagnostic mentions the wrong contextual type conversion problem protocol A_SR_5030 { associatedtype Value func map<U>(_ t : @escaping (Self.Value) -> U) -> B_SR_5030<U> } struct B_SR_5030<T> : A_SR_5030 { typealias Value = T func map<U>(_ t : @escaping (T) -> U) -> B_SR_5030<U> { fatalError() } } func sr5030_exFalso<T>() -> T { fatalError() } extension A_SR_5030 { func foo() -> B_SR_5030<Int> { let tt : B_SR_5030<Int> = sr5030_exFalso() return tt.map { x in (idx: x) } // expected-error@-1 {{cannot convert value of type '(idx: (Int))' to closure result type 'Int'}} } } // rdar://problem/33296619 let u = rdar33296619().element //expected-error {{use of unresolved identifier 'rdar33296619'}} [1].forEach { _ in _ = "\(u)" _ = 1 + "hi" // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists}} } class SR5666 { var property: String? } func testSR5666(cs: [SR5666?]) -> [String?] { return cs.map({ c in let a = c.propertyWithTypo ?? "default" // expected-error@-1 {{value of type 'SR5666?' has no member 'propertyWithTypo'}} let b = "\(a)" return b }) } // Ensure that we still do the appropriate pointer conversion here. _ = "".withCString { UnsafeMutableRawPointer(mutating: $0) } // rdar://problem/34077439 - Crash when pre-checking bails out and // leaves us with unfolded SequenceExprs inside closure body. _ = { (offset) -> T in // expected-error {{use of undeclared type 'T'}} return offset ? 0 : 0 } struct SR5202<T> { func map<R>(fn: (T) -> R) {} } SR5202<()>().map{ return 0 } SR5202<()>().map{ _ in return 0 } SR5202<Void>().map{ return 0 } SR5202<Void>().map{ _ in return 0 } func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) { var x = item update(&x) } var sr3250_arg = 42 sr3520_2(sr3250_arg) { $0 += 3 } // ok // SR-1976/SR-3073: Inference of inout func sr1976<T>(_ closure: (inout T) -> Void) {} sr1976({ $0 += 2 }) // ok
apache-2.0
7ca8062e4c5b20f3ecd5e7019f9f551d
34.852893
254
0.635563
3.35878
false
false
false
false
apple/swift
SwiftCompilerSources/Sources/Optimizer/ModulePasses/StackProtection.swift
1
19665
//===--- StackProtection.swift --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SIL private let verbose = false private func log(_ message: @autoclosure () -> String) { if verbose { print("### \(message())") } } /// Decides which functions need stack protection. /// /// Sets the `needStackProtection` flags on all function which contain stack-allocated /// values for which an buffer overflow could occur. /// /// Within safe swift code there shouldn't be any buffer overflows. But if the address /// of a stack variable is converted to an unsafe pointer, it's not in the control of /// the compiler anymore. /// This means, if an `alloc_stack` ends up at an `address_to_pointer [stack_protection]`, /// the `alloc_stack`'s function is marked for stack protection. /// Another case is `index_addr [stack_protection]` for non-tail allocated memory. This /// pattern appears if pointer arithmetic is done with unsafe pointers in swift code. /// /// If the origin of an unsafe pointer can only be tracked to a function argument, the /// pass tries to find the root stack allocation for such an argument by doing an /// inter-procedural analysis. If this is not possible and the `enableMoveInoutStackProtection` /// option is set, the fallback is to move the argument into a temporary `alloc_stack` /// and do the unsafe pointer operations on the temporary. let stackProtection = ModulePass(name: "stack-protection", { (context: ModulePassContext) in if !context.options.enableStackProtection { return } var optimization = StackProtectionOptimization(enableMoveInout: context.options.enableMoveInoutStackProtection) optimization.processModule(context) }) /// The stack-protection optimization on function-level. /// /// In contrast to the `stack-protection` pass, this pass doesn't do any inter-procedural /// analysis. It runs at Onone. let functionStackProtection = FunctionPass(name: "function-stack-protection", { (function: Function, context: PassContext) in if !context.options.enableStackProtection { return } var optimization = StackProtectionOptimization(enableMoveInout: context.options.enableMoveInoutStackProtection) optimization.process(function: function, context) }) /// The optimization algorithm. private struct StackProtectionOptimization { private let enableMoveInout: Bool // The following members are nil/not used if this utility is used on function-level. private var moduleContext: ModulePassContext? private var functionUses = FunctionUses() private var functionUsesComputed = false // Functions (other than the currently processed one) which need stack protection, // are added to this array in `findOriginsInCallers`. private var needStackProtection: [Function] = [] init(enableMoveInout: Bool) { self.enableMoveInout = enableMoveInout } /// The main entry point if running on module-level. mutating func processModule(_ moduleContext: ModulePassContext) { self.moduleContext = moduleContext // Collect all functions which need stack protection and insert required moves. for function in moduleContext.functions { moduleContext.transform(function: function) { context in process(function: function, context) } // We cannot modify other functions than the currently processed function in `process(function:)`. // Therefore, if `findOriginsInCallers` finds any callers, which need stack protection, // add the `needStackProtection` flags here. for function in needStackProtection { moduleContext.transform(function: function) { context in function.setNeedsStackProtection(context) } } needStackProtection.removeAll(keepingCapacity: true) } } /// The main entry point if running on function-level. mutating func process(function: Function, _ context: PassContext) { var mustFixStackNesting = false for inst in function.instructions { process(instruction: inst, in: function, mustFixStackNesting: &mustFixStackNesting, context) } if mustFixStackNesting { context.fixStackNesting(function: function) } } /// Checks if `instruction` may be an unsafe instruction which may cause a buffer overflow. /// /// If this is the case, either /// - set the function's `needStackProtection` flag if the relevant allocation is in the /// same function, or /// - if the address is passed as an argument: try to find the origin in its callers and /// add the relevant callers to `self.needStackProtection`, or /// - if the origin is unknown, move the value into a temporary and set the function's /// `needStackProtection` flag. private mutating func process(instruction: Instruction, in function: Function, mustFixStackNesting: inout Bool, _ context: PassContext) { // `withUnsafeTemporaryAllocation(of:capacity:_:)` is compiled to a `builtin "stackAlloc"`. if let bi = instruction as? BuiltinInst, bi.id == .StackAlloc { function.setNeedsStackProtection(context) return } // For example: // %accessBase = alloc_stack $S // %scope = begin_access [modify] %accessBase // %instruction = address_to_pointer [stack_protection] %scope // guard let (accessBase, scope) = instruction.accessBaseToProtect else { return } switch accessBase.isStackAllocated { case .no: // For example: // %baseAddr = global_addr @global break case .yes: // For example: // %baseAddr = alloc_stack $T log("local: \(function.name) -- \(instruction)") function.setNeedsStackProtection(context) case .decidedInCaller(let arg): // For example: // bb0(%baseAddr: $*T): var worklist = ArgumentWorklist(context) defer { worklist.deinitialize() } worklist.push(arg) if findOriginsInCallers(&worklist) == NeedInsertMoves.yes { // We don't know the origin of the function argument. Therefore we need to do the // conservative default which is to move the value to a temporary stack location. if let beginAccess = scope { // If there is an access, we need to move the destination of the `begin_access`. // We should never change the source address of a `begin_access` to a temporary. moveToTemporary(scope: beginAccess, mustFixStackNesting: &mustFixStackNesting, context) } else { moveToTemporary(argument: arg, context) } } case .objectIfStackPromoted(let obj): // For example: // %0 = alloc_ref [stack] $Class // %baseAddr = ref_element_addr %0 : $Class, #Class.field var worklist = ArgumentWorklist(context) defer { worklist.deinitialize() } // If the object is passed as an argument to its function, add those arguments // to the worklist. let (_, foundStackAlloc) = worklist.push(rootsOf: obj) if foundStackAlloc { // The object is created by an `alloc_ref [stack]`. log("objectIfStackPromoted: \(function.name) -- \(instruction)") function.setNeedsStackProtection(context) } // In case the (potentially) stack allocated object is passed via an argument, // process the worklist as we do for indirect arguments (see above). // For example: // bb0(%0: $Class): // %baseAddr = ref_element_addr %0 : $Class, #Class.field if findOriginsInCallers(&worklist) == NeedInsertMoves.yes, let beginAccess = scope { // We don't know the origin of the object. Therefore we need to do the // conservative default which is to move the value to a temporary stack location. moveToTemporary(scope: beginAccess, mustFixStackNesting: &mustFixStackNesting, context) } case .unknown: // TODO: better handling of unknown access bases break } } /// Return value of `findOriginsInCallers()`. enum NeedInsertMoves { // Not all call sites could be identified, and if moves are enabled (`enableMoveInout`) // the original argument should be moved to a temporary. case yes // Either all call sites could be identified, which means that stack protection is done // in the callers, or moves are not enabled (`enableMoveInout` is false). case no } /// Find all origins of function arguments in `worklist`. /// All functions, which allocate such an origin are added to `self.needStackProtection`. /// Returns true if all origins could be found and false, if there are unknown origins. private mutating func findOriginsInCallers(_ worklist: inout ArgumentWorklist) -> NeedInsertMoves { guard let moduleContext = moduleContext else { // Don't do any inter-procedural analysis when used on function-level. return enableMoveInout ? .yes : .no } // Put the resulting functions into a temporary array, because we only add them to // `self.needStackProtection` if we don't return false. var newFunctions = Stack<Function>(moduleContext) defer { newFunctions.deinitialize() } if !functionUsesComputed { functionUses.collect(context: moduleContext) functionUsesComputed = true } while let arg = worklist.pop() { let f = arg.function let uses = functionUses.getUses(of: f) if uses.hasUnknownUses && enableMoveInout { return NeedInsertMoves.yes } for useInst in uses { guard let fri = useInst as? FunctionRefInst else { if enableMoveInout { return NeedInsertMoves.yes } continue } for functionRefUse in fri.uses { guard let apply = functionRefUse.instruction as? ApplySite, let callerArgIdx = apply.callerArgIndex(calleeArgIndex: arg.index) else { if enableMoveInout { return NeedInsertMoves.yes } continue } let callerArg = apply.arguments[callerArgIdx] if callerArg.type.isAddress { // It's an indirect argument. switch callerArg.accessBase.isStackAllocated { case .yes: if !callerArg.function.needsStackProtection { log("alloc_stack in caller: \(callerArg.function.name) -- \(callerArg)") newFunctions.push(callerArg.function) } case .no: break case .decidedInCaller(let callerFuncArg): if !callerFuncArg.convention.isInout { break } // The argumente is itself passed as an argument to its function. // Continue with looking into the callers. worklist.push(callerFuncArg) case .objectIfStackPromoted(let obj): // If the object is passed as an argument to its function, // add those arguments to the worklist. let (foundUnknownRoots, foundStackAlloc) = worklist.push(rootsOf: obj) if foundUnknownRoots && enableMoveInout { return NeedInsertMoves.yes } if foundStackAlloc && !obj.function.needsStackProtection { // The object is created by an `alloc_ref [stack]`. log("object in caller: \(obj.function.name) -- \(obj)") newFunctions.push(obj.function) } case .unknown: if enableMoveInout { return NeedInsertMoves.yes } } } else { // The argument is an object. If the object is itself passed as an argument // to its function, add those arguments to the worklist. let (foundUnknownRoots, foundStackAlloc) = worklist.push(rootsOf: callerArg) if foundUnknownRoots && enableMoveInout { return NeedInsertMoves.yes } if foundStackAlloc && !callerArg.function.needsStackProtection { // The object is created by an `alloc_ref [stack]`. log("object arg in caller: \(callerArg.function.name) -- \(callerArg)") newFunctions.push(callerArg.function) } } } } } needStackProtection.append(contentsOf: newFunctions) return NeedInsertMoves.no } /// Moves the value of an indirect argument to a temporary stack location, if possible. private func moveToTemporary(argument: FunctionArgument, _ context: PassContext) { if !argument.convention.isInout { // We cannot move from a read-only argument. // Also, read-only arguments shouldn't be subject to buffer overflows (because // no one should ever write to such an argument). return } let function = argument.function let entryBlock = function.entryBlock let loc = entryBlock.instructions.first!.location.autoGenerated let builder = Builder(atBeginOf: entryBlock, location: loc, context) let temporary = builder.createAllocStack(argument.type) argument.uses.replaceAll(with: temporary, context) builder.createCopyAddr(from: argument, to: temporary, takeSource: true, initializeDest: true) for block in function.blocks { let terminator = block.terminator if terminator.isFunctionExiting { let exitBuilder = Builder(at: terminator, location: terminator.location.autoGenerated, context) exitBuilder.createCopyAddr(from: temporary, to: argument, takeSource: true, initializeDest: true) exitBuilder.createDeallocStack(temporary) } } log("move addr protection in \(function.name): \(argument)") function.setNeedsStackProtection(context) } /// Moves the value of a `beginAccess` to a temporary stack location, if possible. private func moveToTemporary(scope beginAccess: BeginAccessInst, mustFixStackNesting: inout Bool, _ context: PassContext) { if beginAccess.accessKind != .Modify { // We can only move from a `modify` access. // Also, read-only accesses shouldn't be subject to buffer overflows (because // no one should ever write to such a storage). return } let builder = Builder(after: beginAccess, location: beginAccess.location.autoGenerated, context) let temporary = builder.createAllocStack(beginAccess.type) for use in beginAccess.uses where !(use.instruction is EndAccessInst) { use.instruction.setOperand(at: use.index, to: temporary, context) } for endAccess in beginAccess.endInstructions { let endBuilder = Builder(at: endAccess, location: endAccess.location.autoGenerated, context) endBuilder.createCopyAddr(from: temporary, to: beginAccess, takeSource: true, initializeDest: true) endBuilder.createDeallocStack(temporary) } builder.createCopyAddr(from: beginAccess, to: temporary, takeSource: true, initializeDest: true) log("move object protection in \(beginAccess.function.name): \(beginAccess)") beginAccess.function.setNeedsStackProtection(context) // Access scopes are not necessarily properly nested, which can result in // not properly nested stack allocations. mustFixStackNesting = true } } /// Worklist for inter-procedural analysis of function arguments. private struct ArgumentWorklist : ValueUseDefWalker { var walkUpCache = WalkerCache<SmallProjectionPath>() // Used in `push(rootsOf:)` private var foundStackAlloc = false private var foundUnknownRoots = false // Contains arguments which are already handled and don't need to be put into the worklist again. // Note that this cannot be a `ValueSet`, because argument can be from different functions. private var handled = Set<FunctionArgument>() // The actual worklist. private var list: Stack<FunctionArgument> init(_ context: PassContext) { self.list = Stack(context) } mutating func deinitialize() { list.deinitialize() } mutating func push(_ arg: FunctionArgument) { if handled.insert(arg).0 { list.push(arg) } } /// Pushes all roots of `object`, which are function arguments, to the worklist. /// If the returned `foundUnknownRoots` is true, it means that not all roots of `object` could /// be tracked to a function argument. /// If the returned `foundStackAlloc` than at least one found root is an `alloc_ref [stack]`. mutating func push(rootsOf object: Value) -> (foundUnknownRoots: Bool, foundStackAlloc: Bool) { foundStackAlloc = false foundUnknownRoots = false _ = walkUp(value: object, path: SmallProjectionPath(.anything)) return (foundUnknownRoots, foundStackAlloc) } mutating func pop() -> FunctionArgument? { return list.pop() } // Internal walker function. mutating func rootDef(value: Value, path: Path) -> WalkResult { switch value { case let ar as AllocRefInstBase: if ar.canAllocOnStack { foundStackAlloc = true } case let arg as FunctionArgument: push(arg) default: foundUnknownRoots = true } return .continueWalk } } private extension AccessBase { enum IsStackAllocatedResult { case yes case no case decidedInCaller(FunctionArgument) case objectIfStackPromoted(Value) case unknown } var isStackAllocated: IsStackAllocatedResult { switch self { case .stack: return .yes case .box, .global: return .no case .class(let rea): return .objectIfStackPromoted(rea.operand) case .tail(let rta): return .objectIfStackPromoted(rta.operand) case .argument(let arg): return .decidedInCaller(arg) case .yield, .pointer: return .unknown case .unidentified: // In the rare case of an unidentified access, just ignore it. // This should not happen in regular SIL, anyway. return .no } } } private extension Instruction { /// If the instruction needs stack protection, return the relevant access base and scope. var accessBaseToProtect: (AccessBase, scope: BeginAccessInst?)? { let baseAddr: Value switch self { case let atp as AddressToPointerInst: if !atp.needsStackProtection { return nil } // The result of an `address_to_pointer` may be used in any unsafe way, e.g. // passed to a C function. baseAddr = atp.operand case let ia as IndexAddrInst: if !ia.needsStackProtection { return nil } // `index_addr` is unsafe if not used for tail-allocated elements (e.g. in Array). baseAddr = ia.base default: return nil } let (accessPath, scope) = baseAddr.accessPathWithScope if case .tail = accessPath.base, self is IndexAddrInst { // `index_addr` for tail-allocated elements is the usual case (most likely coming from // Array code). return nil } return (accessPath.base, scope) } } private extension Function { func setNeedsStackProtection(_ context: PassContext) { if !needsStackProtection { set(needStackProtection: true, context) } } }
apache-2.0
28d69388f871b062b2963b3b6700d428
36.96332
113
0.668548
4.794003
false
false
false
false
apple/swift
test/AutoDiff/compiler_crashers_fixed/issue-55333-55334-vjp-emitter-definite-initialization.swift
2
2448
// RUN: %target-build-swift %s // RUN: %target-swift-frontend -emit-sil %s | %FileCheck %s // Test crashes related to differentiation and definite initialization. // https://github.com/apple/swift/issues/55333 // SIL memory lifetime verification error due to `SILCloner::visitAllocStack` // not copying the `[dynamic_lifetime]` attribute // https://github.com/apple/swift/issues/55334 // Debug scope error for pullback struct `struct` instruction generated // by `VJPEmitter` // FIXME: Disabled due to flakiness on Linux (https://github.com/apple/swift/issues/55466), likely related to TF-1197. // REQUIRES: SR13021 import _Differentiation enum Enum { case a } struct Tensor<T>: Differentiable { @noDerivative var x: T @noDerivative var optional: Int? init(_ x: T, _ e: Enum) { self.x = x switch e { case .a: optional = 1 } } // Definite initialization triggers for this initializer. @differentiable(reverse) init(_ x: T, _ other: Self) { self = Self(x, Enum.a) } } // Check that `allock_stack [dynamic_lifetime]` attribute is correctly cloned. // CHECK-LABEL: sil hidden @$s4main6TensorVyACyxGx_ADtcfC : $@convention(method) <T> (@in T, @in Tensor<T>, @thin Tensor<T>.Type) -> @out Tensor<T> { // CHECK: [[SELF_ALLOC:%.*]] = alloc_stack [dynamic_lifetime] $Tensor<T>, var, name "self" // CHECK-LABEL: sil hidden @AD__$s4main6TensorVyACyxGx_ADtcfC__vjp_src_0_wrt_1_l : $@convention(method) <τ_0_0> (@in τ_0_0, @in Tensor<τ_0_0>, @thin Tensor<τ_0_0>.Type) -> (@out Tensor<τ_0_0>, @owned @callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1 for <Tensor<τ_0_0>.TangentVector, Tensor<τ_0_0>.TangentVector>) { // CHECK: [[SELF_ALLOC:%.*]] = alloc_stack [dynamic_lifetime] $Tensor<τ_0_0>, var, name "self" // Original error in https://github.com/apple/swift/issues/55333: // SIL memory lifetime failure in @AD__$s5crash6TensorVyACyxGx_ADtcfC__vjp_src_0_wrt_1_l: memory is not initialized, but should // memory location: %29 = struct_element_addr %5 : $*Tensor<τ_0_0>, #Tensor.x // user: %30 // at instruction: destroy_addr %29 : $*τ_0_0 // id: %30 // Original error in https://github.com/apple/swift/issues/55334: // SIL verification failed: Basic block contains a non-contiguous lexical scope at -Onone: DS == LastSeenScope // %26 = struct $_AD__$s5crash6TensorVyACyxGx_ADtcfC_bb0__PB__src_0_wrt_1_l<τ_0_0> () // users: %34, %28
apache-2.0
9e43fdc8b3c7e1855062d8ba21cb2477
42.446429
349
0.678586
3.060377
false
false
false
false
kreactive/FunctionalJSON
FunctionalJSON/JSONBaseTypes.swift
1
4728
// // JSONBase.swift // AKAds // // Created by Antoine Palazzolo on 20/10/15. // // import Foundation private extension JSONValue { func to<U>(_ : U.Type) throws -> U { guard let underlying = self.underlying else { throw JSONReadError.valueNotFound(self.path) } guard let ret = underlying as? U else {throw JSONReadError.badValueType(self.path)} return ret } } private extension NSNumber { static let jsonRead = JSONRead<NSNumber> { return try $0.to(NSNumber.self) } } extension Int : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.intValue} } extension Int8 : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.int8Value} } extension Int16 : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.int16Value} } extension Int32 : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.int32Value} } extension Int64 : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.int64Value} } extension UInt : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.uintValue} } extension UInt8 : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.uint8Value} } extension UInt16 : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.uint16Value} } extension UInt32 : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.uint32Value} } extension UInt64 : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.uint64Value} } extension Bool : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.boolValue} } extension Float : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.floatValue} } extension Double : JSONReadable { public static let jsonRead = NSNumber.jsonRead.map {$0.doubleValue} } extension String : JSONReadable { public static let jsonRead = JSONRead<String> {try $0.to(String.self)} } public extension Array { internal static func jsonReadValues() -> JSONRead<[JSONValue]> { return JSONRead<[JSONValue]> { v in guard let underlying = v.underlying else {throw JSONReadError.valueNotFound(v.path)} guard let arrayValue = underlying as? NSArray else {throw JSONReadError.badValueType(v.path)} let ret = arrayValue.enumerated().map {JSONValue(underlying: $0.1, path: v.path+$0.0)} return ret } } public static func jsonRead(_ rds : JSONRead<Element>) -> JSONRead<[Element]> { return self.jsonReadValues().map { var validationError = JSONValidationError() var resultAccumulator = [Element]() for jsonValue in $0 { do { try resultAccumulator.append(rds.read(jsonValue)) } catch { validationError.append(error) } } if validationError.content.count > 0 { throw validationError } else { return resultAccumulator } } } public static func jsonReadOpt(_ rds : JSONRead<Element>) -> JSONRead<[Element?]> { return self.jsonReadValues().map { $0.map {try? rds.read($0)}} } public static func jsonReadOptFlat(_ rds : JSONRead<Element>) -> JSONRead<[Element]> { return self.jsonReadValues().map { $0.flatMap {try? rds.read($0)}} } } public extension Array where Element : JSONReadable { public static func jsonRead() -> JSONRead<[Element]> { return self.jsonRead(Element.jsonRead) } public static func jsonReadOpt() -> JSONRead<[Element?]> { return self.jsonReadOpt(Element.jsonRead) } public static func jsonReadOptFlat() -> JSONRead<[Element]> { return self.jsonReadOptFlat(Element.jsonRead) } } public extension JSONValue { public func validate<T : JSONReadable>(_ v : [T].Type) throws -> [T] { return try self.validate(v.jsonRead()) } public func validate<T : JSONReadable>(_ v : [T]?.Type) throws -> [T]? { return try self.validate([T].jsonRead().optional) } public func validate<T : JSONReadable>(_ v : [T?].Type) throws -> [T?] { return try self.validate([T].jsonReadOpt()) } } public extension JSONPath { public func read<T: JSONReadable>(_ v : [T].Type) -> JSONRead<[T]> { return self.read(v.jsonRead()) } public func read<T: JSONReadable>(_ v : [T]?.Type) -> JSONRead<[T]?> { return self.read([T].jsonRead().optional) } public func read<T: JSONReadable>(_ v : [T?].Type) -> JSONRead<[T?]> { return self.read([T].jsonReadOpt()) } }
mit
3709dcaf7883b68173a3dfb3b34a1b04
34.548872
105
0.645093
4.187777
false
false
false
false
wess/reddift
reddift/Model/MediaEmbed.swift
1
865
// // MediaEmbed.swift // reddift // // Created by sonson on 2015/04/21. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation /** Media represents the content which is embeded a link. */ public struct MediaEmbed { /// Height of content. let height:Int /// Width of content. let width:Int /// Information of content. let content:String /// Is content scrolled? let scrolling:Bool /** Update each property with JSON object. :param: json JSON object which is included "t2" JSON. */ public init (json:JSONDictionary) { height = json["height"] as? Int ?? 0 width = json["width"] as? Int ?? 0 content = json["content"] as? String ?? "" scrolling = json["scrolling"] as? Bool ?? false } func toString() -> String { return "{content=\(content)\nsize=\(width)x\(height)}\n" } }
mit
e14b10e842b11a734874ad331b33121c
21.128205
58
0.631518
3.55144
false
false
false
false
benmatselby/sugarcrmcandybar
sugarcrmcandybar/UI/SugarCrmModuleTableCell.swift
1
3017
// // SugarCrmModuleTableCell.swift // sugarcrmcandybar // // Created by Ben Selby on 20/11/2016. // Copyright © 2016 Ben Selby. All rights reserved. // import Foundation import Cocoa /// The view for the module icon part of the results table class SugarCrmModuleTableCell: NSTableCellView { /// The module label within the view /// which will be set to two letters of the module @IBOutlet weak var moduleLabel: NSTextField! /// Set the letters and colouring of the view /// /// - Parameter module: The module of the record of the cell func setModule(module: String) { self.moduleLabel.stringValue = module var bgColour: NSColor = NSColor.black let txtColour: NSColor = NSColor.white var drawBg = true; switch module { case "Ac": // Accounts bgColour = NSColor(srgbRed: 0.2, green: 0.5, blue: 0.05, alpha: 1) case "Cl": // Calls bgColour = NSColor(srgbRed: 0.04, green: 0.21, blue: 0.44, alpha: 1) case "Ca": // Campaigns bgColour = NSColor(srgbRed: 0.27, green: 0.32, blue: 0.03, alpha: 1) case "Cs": // Cases bgColour = NSColor(srgbRed: 0.54, green: 0.05, blue: 0.05, alpha: 1) case "Co": // Contacts bgColour = NSColor(srgbRed: 0.13, green: 0.32, blue: 0.03, alpha: 1) case "Do": // Documents bgColour = NSColor(srgbRed: 0.44, green: 0.11, blue: 0.04, alpha: 1) case "AE": // Emails bgColour = NSColor(srgbRed: 0.07, green: 0.34, blue: 0.72, alpha: 1) case "Fo": // Forecasts bgColour = NSColor(srgbRed: 0.05, green: 0.50, blue: 0.27, alpha: 1) case "Le": // Leads bgColour = NSColor(srgbRed: 0.09, green: 0.43, blue: 0.90, alpha: 1) case "Me": // Meetings bgColour = NSColor(srgbRed: 0.03, green: 0.32, blue: 0.27, alpha: 1) case "Nt": // Notes bgColour = NSColor(srgbRed: 0.06, green: 0.47, blue: 0.60, alpha: 1) case "Op": // Opportunities bgColour = NSColor(srgbRed: 0.43, green: 0.09, blue: 0.90, alpha: 1) case "Pr": // Product bgColour = NSColor(srgbRed: 0.12, green: 0.07, blue: 0.70, alpha: 1) case "Qu": // Quotes bgColour = NSColor(srgbRed: 0.02, green: 0.23, blue: 0.13, alpha: 1) case "Re": // Reports bgColour = NSColor(srgbRed: 0.80, green: 0.20, blue: 0.08, alpha: 1) case "LI": // RevenueLineItems bgColour = NSColor(srgbRed: 0.25, green: 0.05, blue: 0.53, alpha: 1) case "Ts": // Tasks bgColour = NSColor(srgbRed: 0.90, green: 0.09, blue: 0.43, alpha: 1) case "": // No module drawBg = false default: bgColour = NSColor(srgbRed: 0.33, green: 0.33, blue: 0.33, alpha: 1) } self.moduleLabel.drawsBackground = drawBg self.moduleLabel.backgroundColor = bgColour self.moduleLabel.textColor = txtColour } }
mit
96c0f2bd280bc298cd4c30f3e92b5ae8
39.756757
80
0.577255
3.515152
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/ElasticLoadBalancingv2/ElasticLoadBalancingv2_Error.swift
1
10165
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for ElasticLoadBalancingv2 public struct ElasticLoadBalancingv2ErrorType: AWSErrorType { enum Code: String { case aLPNPolicyNotSupportedException = "ALPNPolicyNotFound" case allocationIdNotFoundException = "AllocationIdNotFound" case availabilityZoneNotSupportedException = "AvailabilityZoneNotSupported" case certificateNotFoundException = "CertificateNotFound" case duplicateListenerException = "DuplicateListener" case duplicateLoadBalancerNameException = "DuplicateLoadBalancerName" case duplicateTagKeysException = "DuplicateTagKeys" case duplicateTargetGroupNameException = "DuplicateTargetGroupName" case healthUnavailableException = "HealthUnavailable" case incompatibleProtocolsException = "IncompatibleProtocols" case invalidConfigurationRequestException = "InvalidConfigurationRequest" case invalidLoadBalancerActionException = "InvalidLoadBalancerAction" case invalidSchemeException = "InvalidScheme" case invalidSecurityGroupException = "InvalidSecurityGroup" case invalidSubnetException = "InvalidSubnet" case invalidTargetException = "InvalidTarget" case listenerNotFoundException = "ListenerNotFound" case loadBalancerNotFoundException = "LoadBalancerNotFound" case operationNotPermittedException = "OperationNotPermitted" case priorityInUseException = "PriorityInUse" case resourceInUseException = "ResourceInUse" case ruleNotFoundException = "RuleNotFound" case sSLPolicyNotFoundException = "SSLPolicyNotFound" case subnetNotFoundException = "SubnetNotFound" case targetGroupAssociationLimitException = "TargetGroupAssociationLimit" case targetGroupNotFoundException = "TargetGroupNotFound" case tooManyActionsException = "TooManyActions" case tooManyCertificatesException = "TooManyCertificates" case tooManyListenersException = "TooManyListeners" case tooManyLoadBalancersException = "TooManyLoadBalancers" case tooManyRegistrationsForTargetIdException = "TooManyRegistrationsForTargetId" case tooManyRulesException = "TooManyRules" case tooManyTagsException = "TooManyTags" case tooManyTargetGroupsException = "TooManyTargetGroups" case tooManyTargetsException = "TooManyTargets" case tooManyUniqueTargetGroupsPerLoadBalancerException = "TooManyUniqueTargetGroupsPerLoadBalancer" case unsupportedProtocolException = "UnsupportedProtocol" } private let error: Code public let context: AWSErrorContext? /// initialize ElasticLoadBalancingv2 public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// The specified ALPN policy is not supported. public static var aLPNPolicyNotSupportedException: Self { .init(.aLPNPolicyNotSupportedException) } /// The specified allocation ID does not exist. public static var allocationIdNotFoundException: Self { .init(.allocationIdNotFoundException) } /// The specified Availability Zone is not supported. public static var availabilityZoneNotSupportedException: Self { .init(.availabilityZoneNotSupportedException) } /// The specified certificate does not exist. public static var certificateNotFoundException: Self { .init(.certificateNotFoundException) } /// A listener with the specified port already exists. public static var duplicateListenerException: Self { .init(.duplicateListenerException) } /// A load balancer with the specified name already exists. public static var duplicateLoadBalancerNameException: Self { .init(.duplicateLoadBalancerNameException) } /// A tag key was specified more than once. public static var duplicateTagKeysException: Self { .init(.duplicateTagKeysException) } /// A target group with the specified name already exists. public static var duplicateTargetGroupNameException: Self { .init(.duplicateTargetGroupNameException) } /// The health of the specified targets could not be retrieved due to an internal error. public static var healthUnavailableException: Self { .init(.healthUnavailableException) } /// The specified configuration is not valid with this protocol. public static var incompatibleProtocolsException: Self { .init(.incompatibleProtocolsException) } /// The requested configuration is not valid. public static var invalidConfigurationRequestException: Self { .init(.invalidConfigurationRequestException) } /// The requested action is not valid. public static var invalidLoadBalancerActionException: Self { .init(.invalidLoadBalancerActionException) } /// The requested scheme is not valid. public static var invalidSchemeException: Self { .init(.invalidSchemeException) } /// The specified security group does not exist. public static var invalidSecurityGroupException: Self { .init(.invalidSecurityGroupException) } /// The specified subnet is out of available addresses. public static var invalidSubnetException: Self { .init(.invalidSubnetException) } /// The specified target does not exist, is not in the same VPC as the target group, or has an unsupported instance type. public static var invalidTargetException: Self { .init(.invalidTargetException) } /// The specified listener does not exist. public static var listenerNotFoundException: Self { .init(.listenerNotFoundException) } /// The specified load balancer does not exist. public static var loadBalancerNotFoundException: Self { .init(.loadBalancerNotFoundException) } /// This operation is not allowed. public static var operationNotPermittedException: Self { .init(.operationNotPermittedException) } /// The specified priority is in use. public static var priorityInUseException: Self { .init(.priorityInUseException) } /// A specified resource is in use. public static var resourceInUseException: Self { .init(.resourceInUseException) } /// The specified rule does not exist. public static var ruleNotFoundException: Self { .init(.ruleNotFoundException) } /// The specified SSL policy does not exist. public static var sSLPolicyNotFoundException: Self { .init(.sSLPolicyNotFoundException) } /// The specified subnet does not exist. public static var subnetNotFoundException: Self { .init(.subnetNotFoundException) } /// You've reached the limit on the number of load balancers per target group. public static var targetGroupAssociationLimitException: Self { .init(.targetGroupAssociationLimitException) } /// The specified target group does not exist. public static var targetGroupNotFoundException: Self { .init(.targetGroupNotFoundException) } /// You've reached the limit on the number of actions per rule. public static var tooManyActionsException: Self { .init(.tooManyActionsException) } /// You've reached the limit on the number of certificates per load balancer. public static var tooManyCertificatesException: Self { .init(.tooManyCertificatesException) } /// You've reached the limit on the number of listeners per load balancer. public static var tooManyListenersException: Self { .init(.tooManyListenersException) } /// You've reached the limit on the number of load balancers for your AWS account. public static var tooManyLoadBalancersException: Self { .init(.tooManyLoadBalancersException) } /// You've reached the limit on the number of times a target can be registered with a load balancer. public static var tooManyRegistrationsForTargetIdException: Self { .init(.tooManyRegistrationsForTargetIdException) } /// You've reached the limit on the number of rules per load balancer. public static var tooManyRulesException: Self { .init(.tooManyRulesException) } /// You've reached the limit on the number of tags per load balancer. public static var tooManyTagsException: Self { .init(.tooManyTagsException) } /// You've reached the limit on the number of target groups for your AWS account. public static var tooManyTargetGroupsException: Self { .init(.tooManyTargetGroupsException) } /// You've reached the limit on the number of targets. public static var tooManyTargetsException: Self { .init(.tooManyTargetsException) } /// You've reached the limit on the number of unique target groups per load balancer across all listeners. If a target group is used by multiple actions for a load balancer, it is counted as only one use. public static var tooManyUniqueTargetGroupsPerLoadBalancerException: Self { .init(.tooManyUniqueTargetGroupsPerLoadBalancerException) } /// The specified protocol is not supported. public static var unsupportedProtocolException: Self { .init(.unsupportedProtocolException) } } extension ElasticLoadBalancingv2ErrorType: Equatable { public static func == (lhs: ElasticLoadBalancingv2ErrorType, rhs: ElasticLoadBalancingv2ErrorType) -> Bool { lhs.error == rhs.error } } extension ElasticLoadBalancingv2ErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
7b432c4a5fc1aac96ca4a5e268c3ae1e
60.606061
208
0.746778
5.500541
false
false
false
false
ArchimboldiMao/remotex-iOS
remotex-iOS/Model/JobModel.swift
2
7012
// // JobModel.swift // remotex-iOS // // Created by archimboldi on 10/05/2017. // Copyright © 2017 me.archimboldi. All rights reserved. // import UIKit typealias JSONDictionary = [String: Any] struct JobModel { let jobID: Int let jobTitle: String let price: Double let abstractText: String let createdAt: Date let updatedAt: Date? let releaseAt: Date? let expireAt: Date? let viewCount: Int let voteUp: Int let voteDown: Int let cityName: String? let roles: [RoleModel]? let skills: [SkillModel]? let platform: PlatformModel? let categories: [CategoryModel]? init?(dictionary: JSONDictionary) { guard let jobID = dictionary["id"] as? Int, let jobTitle = dictionary["title"] as? String, let createdAtString = dictionary["created"] as? String, let price = dictionary["price"] as? Double, let viewCount = dictionary["view_count"] as? Int, let voteUp = dictionary["vote_up"] as? Int, let voteDown = dictionary["vote_down"] as? Int else { print("error parsing JSON within JobModel Init") return nil } self.jobID = jobID self.jobTitle = jobTitle self.price = price self.voteUp = voteUp self.voteDown = voteDown self.viewCount = viewCount if let platform = dictionary["platform"] as? JSONDictionary { self.platform = PlatformModel.init(dictionary: platform)! } else { self.platform = nil } self.createdAt = Date.dateWithRFC3339String(from: createdAtString)! if let updatedString = dictionary["updated"] as? String { self.updatedAt = Date.dateWithRFC3339String(from: updatedString) ?? nil } else { self.updatedAt = nil; } if let releaseDateString = dictionary["release_date"] as? String { self.releaseAt = Date.dateWithRFC3339String(from: releaseDateString) ?? nil } else { self.releaseAt = nil; } if let expireDateString = dictionary["expire_date"] as? String { self.expireAt = Date.dateWithRFC3339String(from: expireDateString) ?? nil } else { self.expireAt = nil; } self.cityName = dictionary["city"] as? String ?? "" self.abstractText = dictionary["abstract"] as? String ?? "" if let categories = dictionary["categories"] as? [JSONDictionary] { self.categories = categories.flatMap(CategoryModel.init) } else { self.categories = nil } if let roles = dictionary["roles"] as? [JSONDictionary] { self.roles = roles.flatMap(RoleModel.init) } else { self.roles = nil } if let skills = dictionary["skills"] as? [JSONDictionary] { self.skills = skills.flatMap(SkillModel.init) } else { self.skills = nil } } } extension JobModel { var priceOnScreen: String { if price <= 0 { return "未报价" } else { return NumberFormatter.formatRMBCurrency(value: price) } } var viewCountOnScreen: String { return "浏览\(viewCount)次" } var releaseAtOnScreen: String { if (releaseAt != nil) { let currentCalendar = NSCalendar.current let dayComponents = currentCalendar.dateComponents([.day], from: releaseAt!, to: Date()) if dayComponents.day! >= 1 { return "\(dayComponents.day!)天前发布" } else { let hourComponents = currentCalendar.dateComponents([.hour], from: releaseAt!, to: Date()) if hourComponents.hour! >= 1 { return "\(hourComponents.hour!)小时前发布" } else { return "刚刚发布" } } } else { return "" } } var expireAtOnScreen: String { if (expireAt != nil) { let currentCalendar = NSCalendar.current let dayComponents = currentCalendar.dateComponents([.day], from: Date(), to: expireAt!) if dayComponents.day! >= 1 { return "将于\(dayComponents.day!)天后到期" } else { return "即将到期" } } else { return "" } } func attrStringForTitle(withSize size: CGFloat) -> NSAttributedString { let attr = [ NSForegroundColorAttributeName: Constants.CellLayout.TitleForegroundColor, NSFontAttributeName: UIFont.boldSystemFont(ofSize: size) ] return NSAttributedString.init(string: self.jobTitle, attributes: attr) } func attrStringForPrice(withSize size: CGFloat) -> NSAttributedString { let attr = [ NSForegroundColorAttributeName: Constants.CellLayout.PriceForegroundColor, NSFontAttributeName: UIFont.systemFont(ofSize: size) ] return NSAttributedString.init(string: self.priceOnScreen, attributes: attr) } func attrStringForAbstractText(withSize size: CGFloat) -> NSAttributedString { let attr = [ NSForegroundColorAttributeName: Constants.CellLayout.AbstractForegroundColor, NSFontAttributeName: UIFont.systemFont(ofSize: size) ] return NSAttributedString.init(string: self.abstractText, attributes: attr) } func attrStringForViewCount(withSize size: CGFloat) -> NSAttributedString { let attr = [ NSForegroundColorAttributeName: Constants.CellLayout.DateForegroundColor, NSFontAttributeName: UIFont.systemFont(ofSize: size) ] return NSAttributedString.init(string: self.viewCountOnScreen, attributes: attr) } func attrStringForReleaseAt(withSize size: CGFloat) -> NSAttributedString { let attr = [ NSForegroundColorAttributeName: Constants.CellLayout.DateForegroundColor, NSFontAttributeName: UIFont.systemFont(ofSize: size) ] return NSAttributedString.init(string: self.releaseAtOnScreen, attributes: attr) } func attrStringForExpireAt(withSize size: CGFloat) -> NSAttributedString { let attr = [ NSForegroundColorAttributeName: Constants.CellLayout.DateForegroundColor, NSFontAttributeName: UIFont.systemFont(ofSize: size) ] return NSAttributedString.init(string: self.expireAtOnScreen, attributes: attr) } func attrStringForCityName(withSize size: CGFloat) -> NSAttributedString { let attr = [ NSForegroundColorAttributeName: Constants.CellLayout.TagForegroundColor, NSFontAttributeName: UIFont.systemFont(ofSize: size) ] return NSAttributedString.init(string: self.cityName!, attributes: attr) } }
apache-2.0
05cc58076fb44aed162029c8ab17cb0d
34.65641
346
0.606501
4.973534
false
false
false
false
cheyongzi/MGTV-Swift
MGTV-Swift/Home/View/TemplateCell/Cell/TemplateCollectionViewCell.swift
1
1397
// // TemplateCollectionViewCell.swift // MGTV-Swift // // Created by Che Yongzi on 16/10/10. // Copyright © 2016年 Che Yongzi. All rights reserved. // import UIKit class TemplateCollectionViewCell: UICollectionViewCell { //MARK: - TableViewSource let homeTableViewModel: HomeTableViewModel = HomeTableViewModel([]) //MARK: - Init method override init(frame: CGRect) { super.init(frame: frame); homeTableViewModel.tableView.frame = self.bounds self.addSubview(homeTableViewModel.tableView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Config data func configCell(response: TemplateResponse?) { var datas: [TemplateResponseData] = [] if let templateData = response { datas = templateData.data! } homeTableViewModel.datas = [datas] homeTableViewModel.tableView.reloadData() } func storeOffset() { TemplateDataManager.dataManager.storeOffset(homeTableViewModel.tableView.contentOffset.y, channelId: TemplateDataManager.dataManager.currentChannelId) } func setOffset(_ channelId: String) { homeTableViewModel.tableView.setContentOffset(CGPoint(x: 0, y: TemplateDataManager.dataManager.offset(channelId)), animated: false) } }
mit
858efd7f889bb13b10d0d4b44db9e499
29.304348
158
0.672166
4.857143
false
false
false
false
tjw/swift
test/IRGen/deallocate.swift
2
1027
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir %s | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop // rdar://16979846 class CustomDeallocator { func __getInstanceSizeAndAlignMask() -> (Int, Int) { return (48, 15) } } // CHECK: define hidden swiftcc void @"$S10deallocate17CustomDeallocatorCfD"([[CD:%.*]]* swiftself // CHECK: [[T0:%.*]] = call swiftcc [[OBJECT:%.*]]* @"$S10deallocate17CustomDeallocatorCfd"( // CHECK-NEXT: [[T1:%.*]] = bitcast [[OBJECT]]* [[T0]] to [[CD]]* // CHECK-NEXT: [[T3:%.*]] = call swiftcc { i64, i64 } @"$S10deallocate17CustomDeallocatorC29__getInstanceSizeAndAlignMaskSi_SityF"([[CD]]* [[T1]]) // CHECK-NEXT: [[SIZE:%.*]] = extractvalue { i64, i64 } [[T3]], 0 // CHECK-NEXT: [[ALIGNMASK:%.*]] = extractvalue { i64, i64 } [[T3]], 1 // CHECK-NEXT: [[T4:%.*]] = bitcast [[CD]]* [[T1]] to [[OBJECT]]* // CHECK-NEXT: call void @swift_deallocClassInstance([[OBJECT]]* [[T4]], i64 [[SIZE]], i64 [[ALIGNMASK]]) // CHECK-NEXT: ret void
apache-2.0
9c76b38c9f9b03330aefd80918a49c3f
45.681818
146
0.626095
3.260317
false
false
false
false
kperryua/swift
test/SILGen/closures.swift
2
22830
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s import Swift var zero = 0 // <rdar://problem/15921334> // CHECK-LABEL: sil hidden @_TF8closures46return_local_generic_function_without_captures{{.*}} : $@convention(thin) <A, R> () -> @owned @callee_owned (@in A) -> @out R { func return_local_generic_function_without_captures<A, R>() -> (A) -> R { func f(_: A) -> R { Builtin.int_trap() } // CHECK: [[FN:%.*]] = function_ref @_TFF8closures46return_local_generic_function_without_captures{{.*}} : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0) -> @out τ_0_1 // CHECK: [[FN_WITH_GENERIC_PARAMS:%.*]] = partial_apply [[FN]]<A, R>() : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0) -> @out τ_0_1 // CHECK: return [[FN_WITH_GENERIC_PARAMS]] : $@callee_owned (@in A) -> @out R return f } func return_local_generic_function_with_captures<A, R>(_ a: A) -> (A) -> R { func f(_: A) -> R { _ = a } return f } // CHECK-LABEL: sil hidden @_TF8closures17read_only_capture func read_only_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int func cap() -> Int { return x } return cap() // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures17read_only_capture.*]] : $@convention(thin) (@owned @box Int) -> Int // CHECK: [[RET:%[0-9]+]] = apply [[CAP]]([[XBOX]]) // CHECK: release [[XBOX]] // CHECK: return [[RET]] } // CHECK: sil shared @[[CAP_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : $@box Int): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[X:%[0-9]+]] = load [[XADDR]] // CHECK: release [[XBOX]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @_TF8closures16write_to_capture func write_to_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int // CHECK: [[X2BOX:%[0-9]+]] = alloc_box $Int // CHECK: [[PB:%.*]] = project_box [[X2BOX]] var x2 = x func scribble() { x2 = zero } scribble() // CHECK: [[SCRIB:%[0-9]+]] = function_ref @[[SCRIB_NAME:_TFF8closures16write_to_capture.*]] : $@convention(thin) (@owned @box Int) -> () // CHECK: apply [[SCRIB]]([[X2BOX]]) // CHECK: [[RET:%[0-9]+]] = load [[PB]] // CHECK: release [[X2BOX]] // CHECK: release [[XBOX]] // CHECK: return [[RET]] return x2 } // CHECK: sil shared @[[SCRIB_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : $@box Int): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: copy_addr {{%[0-9]+}} to [[XADDR]] // CHECK: release [[XBOX]] // CHECK: return // CHECK-LABEL: sil hidden @_TF8closures21multiple_closure_refs func multiple_closure_refs(_ x: Int) -> (() -> Int, () -> Int) { var x = x func cap() -> Int { return x } return (cap, cap) // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures21multiple_closure_refs.*]] : $@convention(thin) (@owned @box Int) -> Int // CHECK: [[CAP_CLOSURE_1:%[0-9]+]] = partial_apply [[CAP]] // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_TFF8closures21multiple_closure_refs.*]] : $@convention(thin) (@owned @box Int) -> Int // CHECK: [[CAP_CLOSURE_2:%[0-9]+]] = partial_apply [[CAP]] // CHECK: [[RET:%[0-9]+]] = tuple ([[CAP_CLOSURE_1]] : {{.*}}, [[CAP_CLOSURE_2]] : {{.*}}) // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @_TF8closures18capture_local_func func capture_local_func(_ x: Int) -> () -> () -> Int { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int func aleph() -> Int { return x } func beth() -> () -> Int { return aleph } // CHECK: [[BETH_REF:%[0-9]+]] = function_ref @[[BETH_NAME:_TFF8closures18capture_local_funcFSiFT_FT_SiL_4bethfT_FT_Si]] : $@convention(thin) (@owned @box Int) -> @owned @callee_owned () -> Int // CHECK: [[BETH_CLOSURE:%[0-9]+]] = partial_apply [[BETH_REF]]([[XBOX]]) return beth // CHECK: release [[XBOX]] // CHECK: return [[BETH_CLOSURE]] } // CHECK: sil shared @[[ALEPH_NAME:_TFF8closures18capture_local_funcFSiFT_FT_SiL_5alephfT_Si]] // CHECK: bb0([[XBOX:%[0-9]+]] : $@box Int): // CHECK: sil shared @[[BETH_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : $@box Int): // CHECK: [[ALEPH_REF:%[0-9]+]] = function_ref @[[ALEPH_NAME]] : $@convention(thin) (@owned @box Int) -> Int // CHECK: [[ALEPH_CLOSURE:%[0-9]+]] = partial_apply [[ALEPH_REF]]([[XBOX]]) // CHECK: return [[ALEPH_CLOSURE]] // CHECK-LABEL: sil hidden @_TF8closures22anon_read_only_capture func anon_read_only_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int // CHECK: [[PB:%.*]] = project_box [[XBOX]] return ({ x })() // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures22anon_read_only_capture.*]] : $@convention(thin) (@inout_aliasable Int) -> Int // -- apply expression // CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]]) // -- cleanup // CHECK: release [[XBOX]] // CHECK: return [[RET]] } // CHECK: sil shared @[[CLOSURE_NAME]] // CHECK: bb0([[XADDR:%[0-9]+]] : $*Int): // CHECK: [[X:%[0-9]+]] = load [[XADDR]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @_TF8closures21small_closure_capture func small_closure_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int // CHECK: [[PB:%.*]] = project_box [[XBOX]] return { x }() // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures21small_closure_capture.*]] : $@convention(thin) (@inout_aliasable Int) -> Int // -- apply expression // CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]]) // -- cleanup // CHECK: release [[XBOX]] // CHECK: return [[RET]] } // CHECK: sil shared @[[CLOSURE_NAME]] // CHECK: bb0([[XADDR:%[0-9]+]] : $*Int): // CHECK: [[X:%[0-9]+]] = load [[XADDR]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @_TF8closures35small_closure_capture_with_argument func small_closure_capture_with_argument(_ x: Int) -> (_ y: Int) -> Int { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Int return { x + $0 } // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures35small_closure_capture_with_argument.*]] : $@convention(thin) (Int, @owned @box Int) -> Int // CHECK: retain [[XBOX]] // CHECK: [[ANON_CLOSURE_APP:%[0-9]+]] = partial_apply [[ANON]]([[XBOX]]) // -- return // CHECK: release [[XBOX]] // CHECK: return [[ANON_CLOSURE_APP]] } // CHECK: sil shared @[[CLOSURE_NAME]] : $@convention(thin) (Int, @owned @box Int) -> Int // CHECK: bb0([[DOLLAR0:%[0-9]+]] : $Int, [[XBOX:%[0-9]+]] : $@box Int): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[PLUS:%[0-9]+]] = function_ref @_TFsoi1pFTSiSi_Si{{.*}} // CHECK: [[LHS:%[0-9]+]] = load [[XADDR]] // CHECK: [[RET:%[0-9]+]] = apply [[PLUS]]([[LHS]], [[DOLLAR0]]) // CHECK: release [[XBOX]] // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @_TF8closures24small_closure_no_capture func small_closure_no_capture() -> (_ y: Int) -> Int { // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_TFF8closures24small_closure_no_captureFT_FSiSiU_FSiSi]] : $@convention(thin) (Int) -> Int // CHECK: [[ANON_THICK:%[0-9]+]] = thin_to_thick_function [[ANON]] : ${{.*}} to $@callee_owned (Int) -> Int // CHECK: return [[ANON_THICK]] return { $0 } } // CHECK: sil shared @[[CLOSURE_NAME]] : $@convention(thin) (Int) -> Int // CHECK: bb0([[YARG:%[0-9]+]] : $Int): // CHECK-LABEL: sil hidden @_TF8closures17uncaptured_locals{{.*}} : func uncaptured_locals(_ x: Int) -> (Int, Int) { var x = x // -- locals without captures are stack-allocated // CHECK: bb0([[XARG:%[0-9]+]] : $Int): // CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[PB:%.*]] = project_box [[XADDR]] // CHECK: store [[XARG]] to [[PB]] var y = zero // CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int return (x, y) } class SomeClass { var x : Int = zero init() { x = { self.x }() // Closing over self. } } // Closures within destructors <rdar://problem/15883734> class SomeGenericClass<T> { deinit { var i: Int = zero // CHECK: [[C1REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU_FT_Si : $@convention(thin) (@inout_aliasable Int) -> Int // CHECK: apply [[C1REF]]([[IBOX:%[0-9]+]]) : $@convention(thin) (@inout_aliasable Int) -> Int var x = { i + zero } () // CHECK: [[C2REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU0_FT_Si : $@convention(thin) () -> Int // CHECK: apply [[C2REF]]() : $@convention(thin) () -> Int var y = { zero } () // CHECK: [[C3REF:%[0-9]+]] = function_ref @_TFFC8closures16SomeGenericClassdU1_FT_T_ : $@convention(thin) <τ_0_0> () -> () // CHECK: apply [[C3REF]]<T>() : $@convention(thin) <τ_0_0> () -> () var z = { _ = T.self } () } // CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU_FT_Si : $@convention(thin) (@inout_aliasable Int) -> Int // CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU0_FT_Si : $@convention(thin) () -> Int // CHECK-LABEL: sil shared @_TFFC8closures16SomeGenericClassdU1_FT_T_ : $@convention(thin) <T> () -> () } // This is basically testing that the constraint system ranking // function conversions as worse than others, and therefore performs // the conversion within closures when possible. class SomeSpecificClass : SomeClass {} func takesSomeClassGenerator(_ fn : () -> SomeClass) {} func generateWithConstant(_ x : SomeSpecificClass) { takesSomeClassGenerator({ x }) } // CHECK-LABEL: sil shared @_TFF8closures20generateWithConstant // CHECK: bb0([[T0:%.*]] : $SomeSpecificClass): // CHECK-NEXT: debug_value %0 : $SomeSpecificClass, let, name "x", argno 1 // CHECK-NEXT: [[T1:%.*]] = upcast [[T0]] : $SomeSpecificClass to $SomeClass // CHECK-NEXT: return [[T1]] // Check the annoying case of capturing 'self' in a derived class 'init' // method. We allocate a mutable box to deal with 'self' potentially being // rebound by super.init, but 'self' is formally immutable and so is captured // by value. <rdar://problem/15599464> class Base {} class SelfCapturedInInit : Base { var foo : () -> SelfCapturedInInit // CHECK-LABEL: sil hidden @_TFC8closures18SelfCapturedInInitc{{.*}} : $@convention(method) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit { // CHECK: [[VAL:%.*]] = load {{%.*}} : $*SelfCapturedInInit // CHECK: [[VAL:%.*]] = load {{%.*}} : $*SelfCapturedInInit // CHECK: [[VAL:%.*]] = load {{%.*}} : $*SelfCapturedInInit // CHECK: strong_retain [[VAL]] : $SelfCapturedInInit // CHECK: partial_apply {{%.*}}([[VAL]]) : $@convention(thin) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit override init() { super.init() foo = { self } } } func takeClosure(_ fn: () -> Int) -> Int { return fn() } class TestCaptureList { var x = zero func testUnowned() { let aLet = self takeClosure { aLet.x } takeClosure { [unowned aLet] in aLet.x } takeClosure { [weak aLet] in aLet!.x } var aVar = self takeClosure { aVar.x } takeClosure { [unowned aVar] in aVar.x } takeClosure { [weak aVar] in aVar!.x } takeClosure { self.x } takeClosure { [unowned self] in self.x } takeClosure { [weak self] in self!.x } takeClosure { [unowned newVal = TestCaptureList()] in newVal.x } takeClosure { [weak newVal = TestCaptureList()] in newVal!.x } } } class ClassWithIntProperty { final var x = 42 } func closeOverLetLValue() { let a : ClassWithIntProperty a = ClassWithIntProperty() takeClosure { a.x } } // The let property needs to be captured into a temporary stack slot so that it // is loadable even though we capture the value. // CHECK-LABEL: sil shared @_TFF8closures18closeOverLetLValueFT_T_U_FT_Si // CHECK: bb0(%0 : $ClassWithIntProperty): // CHECK-NEXT: [[TMP:%.*]] = alloc_stack $ClassWithIntProperty, let, name "a", argno 1 // CHECK-NEXT: store %0 to [[TMP]] : $*ClassWithIntProperty // CHECK-NEXT: {{.*}} = load [[TMP]] : $*ClassWithIntProperty // CHECK-NEXT: {{.*}} = ref_element_addr {{.*}} : $ClassWithIntProperty, #ClassWithIntProperty.x // CHECK-NEXT: {{.*}} = load {{.*}} : $*Int // CHECK-NEXT: destroy_addr [[TMP]] : $*ClassWithIntProperty // CHECK-NEXT: dealloc_stack %1 : $*ClassWithIntProperty // CHECK-NEXT: return // Use an external function so inout deshadowing cannot see its body. @_silgen_name("takesNoEscapeClosure") func takesNoEscapeClosure(fn : () -> Int) struct StructWithMutatingMethod { var x = 42 mutating func mutatingMethod() { // This should not capture the refcount of the self shadow. takesNoEscapeClosure { x = 42; return x } } } // Check that the address of self is passed in, but not the refcount pointer. // CHECK-LABEL: sil hidden @_TFV8closures24StructWithMutatingMethod14mutatingMethod // CHECK: bb0(%0 : $*StructWithMutatingMethod): // CHECK: [[CLOSURE:%[0-9]+]] = function_ref @_TFFV8closures24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int // CHECK: partial_apply [[CLOSURE]](%0) : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int // Check that the closure body only takes the pointer. // CHECK-LABEL: sil shared @_TFFV8closures24StructWithMutatingMethod14mutatingMethod{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int { // CHECK: bb0(%0 : $*StructWithMutatingMethod): class SuperBase { func boom() {} } class SuperSub : SuperBase { override func boom() {} // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1a // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1a // CHECK: = apply [[INNER]](%0) // CHECK: return func a() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1a // CHECK: [[CLASS_METHOD:%.*]] = class_method %0 : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]](%0) // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[SUPER]]) // CHECK: return func a1() { self.boom() super.boom() } a1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1b // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1b // CHECK: = apply [[INNER]](%0) // CHECK: return func b() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1b // CHECK: [[INNER:%.*]] = function_ref @_TFFFC8closures8SuperSub1b // CHECK: = apply [[INNER]](%0) // CHECK: return func b1() { // CHECK-LABEL: sil shared @_TFFFC8closures8SuperSub1b // CHECK: [[CLASS_METHOD:%.*]] = class_method %0 : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]](%0) // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[SUPER]]) // CHECK: return func b2() { self.boom() super.boom() } b2() } b1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1c // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1c // CHECK: = partial_apply [[INNER]](%0) // CHECK: return func c() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1c // CHECK: [[CLASS_METHOD:%.*]] = class_method %0 : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]](%0) // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[SUPER]]) // CHECK: return let c1 = { () -> Void in self.boom() super.boom() } c1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1d // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1d // CHECK: = partial_apply [[INNER]](%0) // CHECK: return func d() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1d // CHECK: [[INNER:%.*]] = function_ref @_TFFFC8closures8SuperSub1d // CHECK: = apply [[INNER]](%0) // CHECK: return let d1 = { () -> Void in // CHECK-LABEL: sil shared @_TFFFC8closures8SuperSub1d // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[SUPER]]) // CHECK: return func d2() { super.boom() } d2() } d1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1e // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1e // CHECK: = apply [[INNER]](%0) // CHECK: return func e() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1e // CHECK: [[INNER:%.*]] = function_ref @_TFFFC8closures8SuperSub1e // CHECK: = partial_apply [[INNER]](%0) // CHECK: return func e1() { // CHECK-LABEL: sil shared @_TFFFC8closures8SuperSub1e // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[SUPER]]) // CHECK: return let e2 = { super.boom() } e2() } e1() } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1f // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1f // CHECK: = partial_apply [[INNER]](%0) // CHECK: return func f() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1f // CHECK: [[INNER:%.*]] = function_ref @_TFFFC8closures8SuperSub1f // CHECK: = partial_apply [[INNER]](%0) // CHECK: return let f1 = { // CHECK-LABEL: sil shared [transparent] @_TFFFC8closures8SuperSub1f // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[SUPER]]) // CHECK: return nil ?? super.boom() } } // CHECK-LABEL: sil hidden @_TFC8closures8SuperSub1g // CHECK: [[INNER:%.*]] = function_ref @_TFFC8closures8SuperSub1g // CHECK: = apply [[INNER]](%0) // CHECK: return func g() { // CHECK-LABEL: sil shared @_TFFC8closures8SuperSub1g // CHECK: [[INNER:%.*]] = function_ref @_TFFFC8closures8SuperSub1g // CHECK: = partial_apply [[INNER]](%0) // CHECK: return func g1() { // CHECK-LABEL: sil shared [transparent] @_TFFFC8closures8SuperSub1g // CHECK: [[SUPER:%.*]] = upcast %0 : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_TFC8closures9SuperBase4boomfT_T_ : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[SUPER]]) // CHECK: return nil ?? super.boom() } g1() } } // CHECK-LABEL: sil hidden @_TFC8closures24UnownedSelfNestedCapture13nestedCapture{{.*}} : $@convention(method) (@guaranteed UnownedSelfNestedCapture) -> () // CHECK: [[OUTER_SELF_CAPTURE:%.*]] = alloc_box $@sil_unowned UnownedSelfNestedCapture // CHECK: [[PB:%.*]] = project_box [[OUTER_SELF_CAPTURE]] // CHECK: [[UNOWNED_SELF:%.*]] = ref_to_unowned [[SELF_PARAM:%.*]] : // -- TODO: A lot of fussy r/r traffic and owned/unowned conversions here. // -- strong +1, unowned +1 // CHECK: unowned_retain [[UNOWNED_SELF]] // CHECK: store [[UNOWNED_SELF]] to [[PB]] // CHECK: [[UNOWNED_SELF:%.*]] = load [[PB]] // -- strong +2, unowned +1 // CHECK: strong_retain_unowned [[UNOWNED_SELF]] // CHECK: [[SELF:%.*]] = unowned_to_ref [[UNOWNED_SELF]] // CHECK: [[UNOWNED_SELF2:%.*]] = ref_to_unowned [[SELF]] // -- strong +2, unowned +2 // CHECK: unowned_retain [[UNOWNED_SELF2]] // -- strong +1, unowned +2 // CHECK: strong_release [[SELF]] // -- closure takes unowned ownership // CHECK: [[OUTER_CLOSURE:%.*]] = partial_apply {{%.*}}([[UNOWNED_SELF2]]) // -- call consumes closure // -- strong +1, unowned +1 // CHECK: [[INNER_CLOSURE:%.*]] = apply [[OUTER_CLOSURE]] // CHECK: [[CONSUMED_RESULT:%.*]] = apply [[INNER_CLOSURE]]() // CHECK: strong_release [[CONSUMED_RESULT]] // -- releases unowned self in box // -- strong +1, unowned +0 // CHECK: strong_release [[OUTER_SELF_CAPTURE]] // -- strong +0, unowned +0 // CHECK: return // -- outer closure // -- strong +0, unowned +1 // CHECK-LABEL: sil shared @_TFFC8closures24UnownedSelfNestedCapture13nestedCapture // -- strong +0, unowned +2 // CHECK: unowned_retain [[CAPTURED_SELF:%.*]] : // -- closure takes ownership of unowned ref // CHECK: [[INNER_CLOSURE:%.*]] = partial_apply {{%.*}}([[CAPTURED_SELF]]) // -- strong +0, unowned +1 (claimed by closure) // CHECK: unowned_release [[CAPTURED_SELF]] // CHECK: return [[INNER_CLOSURE]] // -- inner closure // -- strong +0, unowned +1 // CHECK-LABEL: sil shared @_TFFFC8closures24UnownedSelfNestedCapture13nestedCapture // -- strong +1, unowned +1 // CHECK: strong_retain_unowned [[CAPTURED_SELF:%.*]] : // CHECK: [[SELF:%.*]] = unowned_to_ref [[CAPTURED_SELF]] // -- strong +1, unowned +0 (claimed by return) // CHECK: unowned_release [[CAPTURED_SELF]] // CHECK: return [[SELF]] class UnownedSelfNestedCapture { func nestedCapture() { {[unowned self] in { self } }()() } } // Check that capturing 'self' via a 'super' call also captures the generic // signature if the base class is concrete and the derived class is generic class ConcreteBase { func swim() {} } // CHECK-LABEL: sil shared @_TFFC8closures14GenericDerived4swimFT_T_U_FT_T_ : $@convention(thin) <Ocean> (@owned GenericDerived<Ocean>) -> () // CHECK: [[SUPER:%.*]] = upcast %0 : $GenericDerived<Ocean> to $ConcreteBase // CHECK: [[METHOD:%.*]] = function_ref @_TFC8closures12ConcreteBase4swimfT_T_ // CHECK: apply [[METHOD]]([[SUPER]]) : $@convention(method) (@guaranteed ConcreteBase) -> () class GenericDerived<Ocean> : ConcreteBase { override func swim() { withFlotationAid { super.swim() } } func withFlotationAid(_ fn: () -> ()) {} } // Don't crash on this func r25993258_helper(_ fn: (inout Int, Int) -> ()) {} func r25993258() { r25993258_helper { _ in () } }
apache-2.0
6a8e9f48159a010c099024d282041eab
37.612521
195
0.599825
3.445568
false
false
false
false
SergeMaslyakov/audio-player
app/src/utils/TimeFormatter.swift
1
861
// // TimeFormatter.swift // AudioPlayer // // Created by Serge Maslyakov on 07/07/2017. // Copyright (c) 2017 Maslyakov. All rights reserved. // import Foundation enum TimeFormatter { static func hmsFrom(seconds: Int) -> String { func stringify(value: Int) -> String { return value < 10 ? "0\(value)" : "\(value)" } let h = stringify(value: seconds / 3600) let m = stringify(value: (seconds % 3600) / 60) let s = stringify(value: (seconds % 3600) % 60) return "\(h):\(m):\(s)" } static func msFrom(seconds: Int) -> String { func stringify(value: Int) -> String { return value < 10 ? "0\(value)" : "\(value)" } let m = "\((seconds % 3600) / 60)" let s = stringify(value: (seconds % 3600) % 60) return "\(m):\(s)" } }
apache-2.0
618e4698af0f20cb9fdbb41dec58a90b
21.076923
56
0.53194
3.727273
false
false
false
false
Brightify/ReactantUI
Sources/Tokenizer/Properties/Descriptions/ValuePropertyDescription.swift
1
2784
// // ValuePropertyDescription.swift // ReactantUI // // Created by Matous Hybl on 05/09/2017. // Copyright © 2017 Brightify. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit #endif /** * Property description describing a property using a single XML attribute. */ public struct ValuePropertyDescription<T: AttributeSupportedPropertyType>: TypedPropertyDescription { public typealias ValueType = T public let namespace: [PropertyContainer.Namespace] public let name: String /** * Get a property using the dictionary passed. * - parameter properties: **[name: property]** dictionary to search in * - returns: found property's value if found, nil otherwise */ public func get(from properties: [String: Property]) -> T? { let property = getProperty(from: properties) return property?.value } /** * Set a property's value from the dictionary passed. * A new property is created if no property is found. * - parameter value: value to be set to the property * - parameter properties: **[name: property]** dictionary to search in */ public func set(value: T, to properties: inout [String: Property]) { var property: ValueProperty<T> if let storedProperty = getProperty(from: properties) { property = storedProperty } else { property = ValueProperty(namespace: namespace, name: name, description: self, value: value) } property.value = value setProperty(property, to: &properties) } /** * Gets a property from the **[name: property]** dictionary passed or nil. * - parameter dictionary: properties dictionary * - returns: found property or nil */ private func getProperty(from dictionary: [String: Property]) -> ValueProperty<T>? { return dictionary[dictionaryKey()] as? ValueProperty<T> } /** * Inserts the property passed into the dictionary of properties. * - parameter property: property to insert * - parameter dictionary: **[name: property]** dictionary to insert into */ private func setProperty(_ property: Property, to dictionary: inout [String: Property]) { dictionary[dictionaryKey()] = property } private func dictionaryKey() -> String { return namespace.resolvedAttributeName(name: name) } } extension ValuePropertyDescription: AttributePropertyDescription /*where T: AttributeSupportedPropertyType*/ { public func materialize(attributeName: String, value: String) throws -> Property { let materializedValue = try T.materialize(from: value) return ValueProperty(namespace: namespace, name: name, description: self, value: materializedValue) } }
mit
7d060192da5bffb0f242df4629fdfabb
33.358025
110
0.678764
4.781787
false
false
false
false
nathawes/swift
test/AutoDiff/Sema/differentiable_func_type.swift
6
13007
// RUN: %target-swift-frontend -typecheck -verify %s import _Differentiation //===----------------------------------------------------------------------===// // Basic @differentiable function types. //===----------------------------------------------------------------------===// // expected-error @+1 {{@differentiable attribute only applies to function types}} let _: @differentiable Float let _: @differentiable (Float) -> Float let _: @differentiable (Float) throws -> Float //===----------------------------------------------------------------------===// // Type differentiability //===----------------------------------------------------------------------===// struct NonDiffType { var x: Int } // FIXME: Properly type-check parameters and the result's differentiability // expected-error @+1 {{parameter type 'NonDiffType' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}} let _: @differentiable (NonDiffType) -> Float // Emit `@noDerivative` fixit iff there is at least one valid differentiability parameter. // expected-error @+1 {{parameter type 'NonDiffType' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'; did you want to add '@noDerivative' to this parameter?}} {{32-32=@noDerivative }} let _: @differentiable (Float, NonDiffType) -> Float // expected-error @+1 {{result type 'NonDiffType' does not conform to 'Differentiable' and satisfy 'NonDiffType == NonDiffType.TangentVector', but the enclosing function type is '@differentiable(linear)'}} let _: @differentiable(linear) (Float) -> NonDiffType // Emit `@noDerivative` fixit iff there is at least one valid linearity parameter. // expected-error @+1 {{parameter type 'NonDiffType' does not conform to 'Differentiable' and satisfy 'NonDiffType == NonDiffType.TangentVector', but the enclosing function type is '@differentiable(linear)'; did you want to add '@noDerivative' to this parameter?}} {{40-40=@noDerivative }} let _: @differentiable(linear) (Float, NonDiffType) -> Float // expected-error @+1 {{result type 'NonDiffType' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}} let _: @differentiable (Float) -> NonDiffType // expected-error @+1 {{result type 'NonDiffType' does not conform to 'Differentiable' and satisfy 'NonDiffType == NonDiffType.TangentVector', but the enclosing function type is '@differentiable(linear)'}} let _: @differentiable(linear) (Float) -> NonDiffType let _: @differentiable(linear) (Float) -> Float // expected-error @+1 {{result type '@differentiable (U) -> Float' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}} func test1<T: Differentiable, U: Differentiable>(_: @differentiable (T) -> @differentiable (U) -> Float) {} // expected-error @+1 {{result type '(U) -> Float' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}} func test2<T: Differentiable, U: Differentiable>(_: @differentiable (T) -> (U) -> Float) {} // expected-error @+2 {{result type 'Int' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}} // expected-error @+1 {{result type '@differentiable (U) -> Int' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}} func test3<T: Differentiable, U: Differentiable>(_: @differentiable (T) -> @differentiable (U) -> Int) {} // expected-error @+1 {{result type '(U) -> Int' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}} func test4<T: Differentiable, U: Differentiable>(_: @differentiable (T) -> (U) -> Int) {} //===----------------------------------------------------------------------===// // Function conversion //===----------------------------------------------------------------------===// /// Function with similar signature as `gradient`, for testing purposes. func fakeGradient<T, U: FloatingPoint>(of f: @differentiable (T) -> U) {} func takesOpaqueClosure(f: @escaping (Float) -> Float) { // expected-note @-1 {{did you mean to take a '@differentiable' closure?}} {{38-38=@differentiable }} // expected-error @+1 {{a '@differentiable' function can only be formed from a reference to a 'func' or 'init' or a literal closure}} fakeGradient(of: f) } let globalAddOne: (Float) -> Float = { $0 + 1 } // expected-error @+1 {{a '@differentiable' function can only be formed from a reference to a 'func' or 'init' or a literal closure}} fakeGradient(of: globalAddOne) func someScope() { let localAddOne: (Float) -> Float = { $0 + 1 } // expected-error @+1 {{a '@differentiable' function can only be formed from a reference to a 'func' or 'init' or a literal closure}} fakeGradient(of: globalAddOne) // expected-error @+1 {{a '@differentiable' function can only be formed from a reference to a 'func' or 'init' or a literal closure}} fakeGradient(of: localAddOne) // The following case is okay during type checking, but will fail in the AD transform. fakeGradient { localAddOne($0) } } func addOne(x: Float) -> Float { x + 1 } fakeGradient(of: addOne) // okay extension Float { static func addOne(x: Float) -> Float { x + 1 } func addOne(x: Float) -> Float { x + 1 } } fakeGradient(of: Float.addOne) // okay fakeGradient(of: Float(1.0).addOne) // okay // TODO(TF-908): Remove this test once linear-to-differentiable conversion is supported. func linearToDifferentiable(_ f: @escaping @differentiable(linear) (Float) -> Float) { // expected-error @+1 {{conversion from '@differentiable(linear)' to '@differentiable' is not yet supported}} _ = f as @differentiable (Float) -> Float } func differentiableToLinear(_ f: @escaping @differentiable (Float) -> Float) { // expected-error @+1 {{a '@differentiable(linear)' function can only be formed from a reference to a 'func' or 'init' or a literal closure}} _ = f as @differentiable(linear) (Float) -> Float } struct Struct: Differentiable { var x: Float } let _: @differentiable (Float) -> Struct = Struct.init //===----------------------------------------------------------------------===// // Parameter selection (@noDerivative) //===----------------------------------------------------------------------===// // expected-error @+1 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}} let _: @noDerivative Float // expected-error @+1 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}} let _: (@noDerivative Float) -> Float // expected-error @+1 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}} let _: (@noDerivative Float, Float) -> Float let _: @differentiable (Float, @noDerivative Float) -> Float // okay // expected-error @+1 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}} let _: (Float) -> @noDerivative Float // expected-error @+1 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}} let _: @differentiable (Float) -> @noDerivative Float // expected-error @+2 {{'@noDerivative' may only be used on parameters of '@differentiable' function types}} // expected-error @+1 {{'@noDerivative' must not be used on variadic parameters}} let _: (Float, @noDerivative Float...) -> Float let _: @differentiable (@noDerivative Float, Float) -> Float // expected-error @+1 {{'@noDerivative' must not be used on variadic parameters}} let _: @differentiable (Float, @noDerivative Float...) -> Float //===----------------------------------------------------------------------===// // Inferred conformances //===----------------------------------------------------------------------===// let diffFunc: @differentiable (Float) -> Float let linearFunc: @differentiable(linear) (Float) -> Float func inferredConformances<T, U>(_: @differentiable (T) -> U) {} func inferredConformancesLinear<T, U>(_: @differentiable(linear) (T) -> U) {} inferredConformances(diffFunc) inferredConformancesLinear(linearFunc) func inferredConformancesResult<T, U>() -> @differentiable (T) -> U {} func inferredConformancesResultLinear<T, U>() -> @differentiable(linear) (T) -> U {} let diffFuncWithNondiff: @differentiable (Float, @noDerivative Int) -> Float let linearFuncWithNondiff: @differentiable(linear) (Float, @noDerivative Int) -> Float func inferredConformances<T, U, V>(_: @differentiable (T, @noDerivative U) -> V) {} func inferredConformancesLinear<T, U, V>(_: @differentiable(linear) (T, @noDerivative U) -> V) {} inferredConformances(diffFuncWithNondiff) inferredConformancesLinear(linearFuncWithNondiff) struct Vector<T> { var x, y: T } extension Vector: Equatable where T: Equatable {} extension Vector: AdditiveArithmetic where T: AdditiveArithmetic { static var zero: Self { fatalError() } static func + (lhs: Self, rhs: Self) -> Self { fatalError() } static func - (lhs: Self, rhs: Self) -> Self { fatalError() } } extension Vector: Differentiable where T: Differentiable { struct TangentVector: Equatable, AdditiveArithmetic, Differentiable { var x, y: T.TangentVector static var zero: Self { fatalError() } static func + (lhs: Self, rhs: Self) -> Self { fatalError() } static func - (lhs: Self, rhs: Self) -> Self { fatalError() } typealias TangentVector = Self } mutating func move(along direction: TangentVector) { fatalError() } } // expected-note@+1 2 {{found this candidate}} func inferredConformancesGeneric<T, U>(_: @differentiable (Vector<T>) -> Vector<U>) {} // expected-note @+5 2 {{found this candidate}} // expected-error @+4 {{generic signature requires types 'Vector<T>' and 'Vector<T>.TangentVector' to be the same}} // expected-error @+3 {{generic signature requires types 'Vector<U>' and 'Vector<U>.TangentVector' to be the same}} // expected-error @+2 {{parameter type 'Vector<T>' does not conform to 'Differentiable' and satisfy 'Vector<T> == Vector<T>.TangentVector', but the enclosing function type is '@differentiable(linear)'}} // expected-error @+1 {{result type 'Vector<U>' does not conform to 'Differentiable' and satisfy 'Vector<U> == Vector<U>.TangentVector', but the enclosing function type is '@differentiable(linear)'}} func inferredConformancesGenericLinear<T, U>(_: @differentiable(linear) (Vector<T>) -> Vector<U>) {} func nondiff(x: Vector<Int>) -> Vector<Int> {} // TODO(diagnostics): Ambiguity notes for two following calls should talk about `T` and `U` both not conforming to `Differentiable` // but we currently have to way to coalesce notes multiple fixes in to a single note. // expected-error @+1 {{no exact matches in call to global function 'inferredConformancesGeneric'}} inferredConformancesGeneric(nondiff) // expected-error @+1 {{no exact matches in call to global function 'inferredConformancesGenericLinear'}} inferredConformancesGenericLinear(nondiff) func diff(x: Vector<Float>) -> Vector<Float> {} inferredConformancesGeneric(diff) // okay! func inferredConformancesGenericResult<T, U>() -> @differentiable (Vector<T>) -> Vector<U> {} // expected-error @+4 {{generic signature requires types 'Vector<T>' and 'Vector<T>.TangentVector' to be the same}} // expected-error @+3 {{generic signature requires types 'Vector<U>' and 'Vector<U>.TangentVector' to be the same}} // expected-error @+2 {{parameter type 'Vector<T>' does not conform to 'Differentiable' and satisfy 'Vector<T> == Vector<T>.TangentVector', but the enclosing function type is '@differentiable(linear)'}} // expected-error @+1 {{result type 'Vector<U>' does not conform to 'Differentiable' and satisfy 'Vector<U> == Vector<U>.TangentVector', but the enclosing function type is '@differentiable(linear)'}} func inferredConformancesGenericResultLinear<T, U>() -> @differentiable(linear) (Vector<T>) -> Vector<U> {} struct Linear<T> { var x, y: T } extension Linear: Equatable where T: Equatable {} extension Linear: AdditiveArithmetic where T: AdditiveArithmetic {} extension Linear: Differentiable where T: Differentiable, T == T.TangentVector { typealias TangentVector = Self } // expected-note @+1 2 {{found this candidate}} func inferredConformancesGeneric<T, U>(_: @differentiable (Linear<T>) -> Linear<U>) {} // expected-note @+1 2 {{found this candidate}} func inferredConformancesGenericLinear<T, U>(_: @differentiable(linear) (Linear<T>) -> Linear<U>) {} func nondiff(x: Linear<Int>) -> Linear<Int> {} // expected-error @+1 {{no exact matches in call to global function 'inferredConformancesGeneric'}} inferredConformancesGeneric(nondiff) // expected-error @+1 {{no exact matches in call to global function 'inferredConformancesGenericLinear'}} inferredConformancesGenericLinear(nondiff) func diff(x: Linear<Float>) -> Linear<Float> {} inferredConformancesGeneric(diff) // okay! func inferredConformancesGenericResult<T, U>() -> @differentiable (Linear<T>) -> Linear<U> {} func inferredConformancesGenericResultLinear<T, U>() -> @differentiable(linear) (Linear<T>) -> Linear<U> {}
apache-2.0
b159e645ada61c10b9e6c72261845008
54.824034
289
0.679019
4.413641
false
false
false
false
ngageoint/mage-ios
MageTests/Mocks/MockCLLocationManager.swift
1
2822
// // MockCLLocationManager.swift // MAGETests // // Created by Daniel Barela on 4/13/21. // Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import CoreLocation class MockCLHeading : CLHeading { var mockedMagneticHeading: CLLocationDirection = 212.3134 var mockedTrueHeading: CLLocationDirection = 231.43123 override var magneticHeading: CLLocationDirection { return mockedMagneticHeading; } override var trueHeading: CLLocationDirection { return mockedTrueHeading; } override init() { super.init(); } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class MockCLLocationManager : CLLocationManager { var mockedLocation: CLLocation? var mockedHeading: CLHeading? var _authorizationStatus: CLAuthorizationStatus = .authorizedAlways var _delegate: CLLocationManagerDelegate? public var updatingHeading: Bool = false public var updatingLocation: Bool = false override var authorizationStatus: CLAuthorizationStatus { get { return _authorizationStatus } set { _authorizationStatus = newValue } } override var delegate: CLLocationManagerDelegate? { get { return _delegate } set { _delegate = newValue _delegate?.locationManagerDidChangeAuthorization?(self) } } override init() { mockedLocation = CLLocation(coordinate: CLLocationCoordinate2D(latitude: 40.008, longitude: -105.2677), altitude: 1625.8, horizontalAccuracy: 5.2, verticalAccuracy: 1.3, course: 200, courseAccuracy: 12.0, speed: 254.0, speedAccuracy: 15.0, timestamp: Date()); mockedHeading = MockCLHeading(); super.init(); } func updateMockedLocation(location: CLLocation) { mockedLocation = location if updatingLocation { delegate?.locationManager?(self, didUpdateLocations: [location]) } } func updateMockedHeading(heading: CLHeading) { mockedHeading = heading if updatingHeading { delegate?.locationManager?(self, didUpdateHeading: heading) } } override var location: CLLocation? { return mockedLocation; } override var heading: CLHeading? { return mockedHeading; } override func stopUpdatingHeading() { updatingHeading = false } override func startUpdatingHeading() { updatingHeading = true } override func stopUpdatingLocation() { updatingLocation = false } override func startUpdatingLocation() { updatingLocation = true } }
apache-2.0
b5eb64bec4f0bd8cf5ee95ac32f66bbf
25.866667
267
0.643034
5.373333
false
false
false
false
DivineDominion/mac-licensing-fastspring-cocoafob
No-Trial-Verify-at-Start/MyNewApp/LicenseChangeBroadcaster.swift
1
1594
// Copyright (c) 2015-2019 Christian Tietze // // See the file LICENSE for copying permission. import Foundation public typealias UserInfo = [AnyHashable: Any] extension Licensing { public func userInfo() -> UserInfo { switch self { case .unregistered: return ["registered" : false] case let .registered(license): return [ "registered" : true, "name" : license.name, "licenseCode" : license.licenseCode ] } } public init?(fromUserInfo userInfo: UserInfo) { guard let registered = userInfo["registered"] as? Bool else { return nil } if !registered { self = .unregistered return } guard let name = userInfo["name"] as? String, let licenseCode = userInfo["licenseCode"] as? String else { return nil } self = .registered(License(name: name, licenseCode: licenseCode)) } } extension Licensing { public static let licenseChangedNotification: Notification.Name = Notification.Name(rawValue: "License Changed") } public class LicenseChangeBroadcaster { public lazy var notificationCenter: NotificationCenter = NotificationCenter.default public init() { } public func broadcast(_ licensing: Licensing) { notificationCenter.post( name: Licensing.licenseChangedNotification, object: self, userInfo: licensing.userInfo()) } }
mit
cff4b0927c9d2bcff2f7e9d48155aadb
25.566667
116
0.584065
5.331104
false
false
false
false
shajrawi/swift
validation-test/stdlib/CollectionCompatibility.swift
1
3927
// RUN: rm -rf %t ; mkdir -p %t // RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-codesign %t/a.out4 && %target-run %t/a.out4 // RUN: %target-build-swift %s -o %t/a.out42 -swift-version 4.2 && %target-codesign %t/a.out42 && %target-run %t/a.out42 // REQUIRES: executable_test // Requires swift-version 4 // UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic import StdlibUnittest import StdlibCollectionUnittest //===--- MyCollection -----------------------------------------------------===// /// A simple collection that attempts to use an Int16 IndexDistance struct MyCollection<Element>: Collection { var _elements: [Element] typealias IndexDistance = Int16 typealias Index = Int16 var startIndex: Index { return 0 } var endIndex: Index { return numericCast(_elements.count) } subscript(i: Index) -> Element { return _elements[Int(i)] } func index(after: Index) -> Index { return after+1 } } //===--- MyBidiCollection -------------------------------------------------===// /// A simple collection that doesn't declare an IndexDistance struct MyBidiCollection<Element>: BidirectionalCollection { var _elements: [Element] typealias Index = Int64 var startIndex: Index { return 0 } var endIndex: Index { return numericCast(_elements.count) } subscript(i: Index) -> Element { return _elements[Int(i)] } func index(after: Index) -> Index { return after+1 } func index(before: Index) -> Index { return before-1 } func index(_ i: Index, advancedBy d: Int64) -> Index { return i+d } } let CollectionDistance = TestSuite("Collection.IndexDistance") CollectionDistance.test("Int16/distance") { let c = MyCollection<Int>(_elements: [1,2,3]) var d: Int16 = c.distance(from: c.startIndex, to: c.endIndex) expectEqual(3, d) expectType(MyCollection<Int>.IndexDistance.self, &d) // without type context, you now get an Int var i = c.distance(from: c.startIndex, to: c.endIndex) expectType(Int.self, &i) } CollectionDistance.test("Int16/advance") { let c = MyCollection<Int>(_elements: [1,2,3]) let d: Int16 = 1 var i = c.index(c.startIndex, offsetBy: d) expectEqual(1, i) c.formIndex(&i, offsetBy: d) expectEqual(2, i) let j = c.index(c.startIndex, offsetBy: d, limitedBy: c.endIndex) expectEqual(1, j) var b = c.formIndex(&i, offsetBy: d, limitedBy: c.endIndex) expectTrue(b) expectEqual(3, i) b = c.formIndex(&i, offsetBy: d+5, limitedBy: c.endIndex) expectFalse(b) expectEqual(3, i) let k = c.index(c.startIndex, offsetBy: d+5, limitedBy: c.endIndex) expectEqual(nil, k) checkCollection(c, [1,2,3], stackTrace: SourceLocStack()) { $0 == $1 } } CollectionDistance.test("Int64/distance") { let c = MyBidiCollection<Int>(_elements: [1,2,3]) var d = c.distance(from: c.startIndex, to: c.endIndex) expectEqual(3, d) expectType(Int.self, &d) expectType(MyBidiCollection<Int>.IndexDistance.self, &d) } CollectionDistance.test("Int64/advance") { let c = MyBidiCollection<Int>(_elements: [1,2,3]) let d: Int16 = 1 var i = c.index(c.startIndex, offsetBy: d) expectEqual(1, i) c.formIndex(&i, offsetBy: d) expectEqual(2, i) let j = c.index(c.startIndex, offsetBy: d, limitedBy: c.endIndex) expectEqual(1, j) var b = c.formIndex(&i, offsetBy: d, limitedBy: c.endIndex) expectTrue(b) expectEqual(3, i) b = c.formIndex(&i, offsetBy: d+5, limitedBy: c.endIndex) expectFalse(b) expectEqual(3, i) let k = c.index(c.startIndex, offsetBy: d+5, limitedBy: c.endIndex) expectEqual(nil, k) checkCollection(c, [1,2,3], stackTrace: SourceLocStack()) { $0 == $1 } checkBidirectionalCollection(c, [1,2,3]) } extension Collection where Index == Int, IndexDistance == Int { var myCount: Int { return distance(from: startIndex, to: endIndex) } } CollectionDistance.test("IndexDistance/constraint") { let n = [1,2,3].myCount expectEqual(3, n) } runAllTests()
apache-2.0
118a1469dc09b59b93ff4af2660149b4
31.454545
120
0.668449
3.367925
false
true
false
false
JeffJin/ios9_notification
twilio/Services/Models/ViewModel/EventDetailsViewModel.swift
2
1084
import Foundation @objc public class EventDetailsViewModel : NSObject { let defaultImage: NSString = "default-no-image.png" //MARK: Properties dynamic var searchText = "" dynamic var previousSearches: [PreviousSearchViewModel] var executeSearch: RACCommand! let title = "Event Search" var previousSearchSelected: RACCommand! var connectionErrors: RACSignal! private let services: ViewModelServices //MARK: Public APIprintln init(services: ViewModelServices) { self.services = services self.previousSearches = [] super.init() setupRac() } func setupRac(){ } public func getImage(imageLink:String) -> UIImage{ if(imageLink != ""){ var url: NSURL = NSURL(string: imageLink)! var imageData = NSData(contentsOfURL: url)! return UIImage(data: imageData)! } else{ return UIImage(named: self.defaultImage as String)! } } }
apache-2.0
0a462a08872379562ad3f0358dce4e84
21.122449
63
0.583026
5.161905
false
false
false
false
lexrus/LTMorphingLabel
LTMorphingLabel/LTMorphingLabel+Anvil.swift
1
11242
// // LTMorphingLabel+Anvil.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2017 Lex Tang, http://lexrus.com // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files // (the “Software”), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit extension LTMorphingLabel { @objc func AnvilLoad() { startClosures["Anvil\(LTMorphingPhases.start)"] = { self.emitterView.removeAllEmitters() guard self.newRects.count > 0 else { return } let centerRect = self.newRects[Int(self.newRects.count / 2)] _ = self.emitterView.createEmitter( "leftSmoke", particleName: "Smoke", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize(width: 1, height: 1) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) layer.renderMode = .unordered cell.emissionLongitude = CGFloat(Double.pi / 2) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 130 cell.birthRate = 60 cell.velocity = CGFloat(80 + Int(arc4random_uniform(60))) cell.velocityRange = 100 cell.yAcceleration = -40 cell.xAcceleration = 70 cell.emissionLongitude = CGFloat(-Double.pi / 2) cell.emissionRange = CGFloat(Double.pi / 4) / 5.0 cell.lifetime = self.morphingDuration * 2.0 cell.spin = 10 cell.alphaSpeed = -0.5 / self.morphingDuration } _ = self.emitterView.createEmitter( "rightSmoke", particleName: "Smoke", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize(width: 1, height: 1) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) layer.renderMode = .unordered cell.emissionLongitude = CGFloat(Double.pi / 2) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 130 cell.birthRate = 60 cell.velocity = CGFloat(80 + Int(arc4random_uniform(60))) cell.velocityRange = 100 cell.yAcceleration = -40 cell.xAcceleration = -70 cell.emissionLongitude = CGFloat(Double.pi / 2) cell.emissionRange = CGFloat(-Double.pi / 4) / 5.0 cell.lifetime = self.morphingDuration * 2.0 cell.spin = -10 cell.alphaSpeed = -0.5 / self.morphingDuration } _ = self.emitterView.createEmitter( "leftFragments", particleName: "Fragment", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize( width: self.font.pointSize, height: 1 ) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3 ) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 40.0 cell.color = self.textColor.cgColor cell.birthRate = 60 cell.velocity = 350 cell.yAcceleration = 0 cell.xAcceleration = CGFloat(10 * Int(arc4random_uniform(10))) cell.emissionLongitude = CGFloat(-Double.pi / 2) cell.emissionRange = CGFloat(Double.pi / 4) / 5.0 cell.alphaSpeed = -2 cell.lifetime = self.morphingDuration } _ = self.emitterView.createEmitter( "rightFragments", particleName: "Fragment", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize( width: self.font.pointSize, height: 1 ) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 40.0 cell.color = self.textColor.cgColor cell.birthRate = 60 cell.velocity = 350 cell.yAcceleration = 0 cell.xAcceleration = CGFloat(-10 * Int(arc4random_uniform(10))) cell.emissionLongitude = CGFloat(Double.pi / 2) cell.emissionRange = CGFloat(-Double.pi / 4) / 5.0 cell.alphaSpeed = -2 cell.lifetime = self.morphingDuration } _ = self.emitterView.createEmitter( "fragments", particleName: "Fragment", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize( width: self.font.pointSize, height: 1 ) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 40.0 cell.color = self.textColor.cgColor cell.birthRate = 60 cell.velocity = 250 cell.velocityRange = CGFloat(Int(arc4random_uniform(20)) + 30) cell.yAcceleration = 500 cell.emissionLongitude = 0 cell.emissionRange = CGFloat(Double.pi / 2) cell.alphaSpeed = -1 cell.lifetime = self.morphingDuration } } progressClosures["Anvil\(LTMorphingPhases.progress)"] = { (index: Int, progress: Float, isNewChar: Bool) in if !isNewChar { return min(1.0, max(0.0, progress)) } let j = Float(sin(Float(index))) * 1.7 return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j)) } effectClosures["Anvil\(LTMorphingPhases.disappear)"] = { char, index, progress in return LTCharacterLimbo( char: char, rect: self.previousRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: 0.0) } effectClosures["Anvil\(LTMorphingPhases.appear)"] = { char, index, progress in var rect = self.newRects[index] if progress < 1.0 { let easingValue = LTEasing.easeOutBounce(progress, 0.0, 1.0) rect.origin.y = CGFloat(Float(rect.origin.y) * easingValue) } if progress > self.morphingDuration * 0.5 { let end = self.morphingDuration * 0.55 self.emitterView.createEmitter( "fragments", particleName: "Fragment", duration: 0.6 ) { (_, _) in }.update { (layer, _) in if progress > end { layer.birthRate = 0 } }.play() self.emitterView.createEmitter( "leftFragments", particleName: "Fragment", duration: 0.6 ) { (_, _) in }.update { (layer, _) in if progress > end { layer.birthRate = 0 } }.play() self.emitterView.createEmitter( "rightFragments", particleName: "Fragment", duration: 0.6 ) { (_, _) in }.update { (layer, _) in if progress > end { layer.birthRate = 0 } }.play() } if progress > self.morphingDuration * 0.63 { let end = self.morphingDuration * 0.7 self.emitterView.createEmitter( "leftSmoke", particleName: "Smoke", duration: 0.6 ) { (_, _) in }.update { (layer, _) in if progress > end { layer.birthRate = 0 } }.play() self.emitterView.createEmitter( "rightSmoke", particleName: "Smoke", duration: 0.6 ) { (_, _) in }.update { (layer, _) in if progress > end { layer.birthRate = 0 } }.play() } return LTCharacterLimbo( char: char, rect: rect, alpha: CGFloat(self.morphingProgress), size: self.font.pointSize, drawingProgress: CGFloat(progress) ) } } }
mit
b3422d3f0059799fa816113d2b1ed76b
41.392453
84
0.467153
5.362291
false
false
false
false
walmartlabs/RxSwift
RxExample/RxExample/Examples/APIWrappers/APIWrappersViewController.swift
11
5939
// // APIWrappersViewController.swift // RxExample // // Created by Carlos García on 8/7/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import UIKit import CoreLocation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif extension UILabel { public override var accessibilityValue: String! { get { return self.text } set { self.text = newValue self.accessibilityValue = newValue } } } class APIWrappersViewController: ViewController { @IBOutlet weak var debugLabel: UILabel! @IBOutlet weak var openActionSheet: UIButton! @IBOutlet weak var openAlertView: UIButton! @IBOutlet weak var bbitem: UIBarButtonItem! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var switcher: UISwitch! @IBOutlet weak var button: UIButton! @IBOutlet weak var slider: UISlider! @IBOutlet weak var textField: UITextField! @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var mypan: UIPanGestureRecognizer! let disposeBag = DisposeBag() let manager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() datePicker.date = NSDate(timeIntervalSince1970: 0) let ash = UIActionSheet(title: "Title", delegate: nil, cancelButtonTitle: "Cancel", destructiveButtonTitle: "OK") let av = UIAlertView(title: "Title", message: "The message", delegate: nil, cancelButtonTitle: "Cancel", otherButtonTitles: "OK", "Two", "Three", "Four", "Five") openActionSheet.rx_tap .subscribeNext { [unowned self] x in ash.showInView(self.view) } .addDisposableTo(disposeBag) openAlertView.rx_tap .subscribeNext { x in av.show() } .addDisposableTo(disposeBag) // MARK: UIActionSheet ash.rx_clickedButtonAtIndex .subscribeNext { [weak self] x in self?.debug("UIActionSheet clickedButtonAtIndex \(x)") } .addDisposableTo(disposeBag) ash.rx_willDismissWithButtonIndex .subscribeNext { [weak self] x in self?.debug("UIActionSheet willDismissWithButtonIndex \(x)") } .addDisposableTo(disposeBag) ash.rx_didDismissWithButtonIndex .subscribeNext { [weak self] x in self?.debug("UIActionSheet didDismissWithButtonIndex \(x)") } .addDisposableTo(disposeBag) // MARK: UIAlertView av.rx_clickedButtonAtIndex .subscribeNext { [weak self] x in self?.debug("UIAlertView clickedButtonAtIndex \(x)") } .addDisposableTo(disposeBag) av.rx_willDismissWithButtonIndex .subscribeNext { [weak self] x in self?.debug("UIAlertView willDismissWithButtonIndex \(x)") } .addDisposableTo(disposeBag) av.rx_didDismissWithButtonIndex .subscribeNext { [weak self] x in self?.debug("UIAlertView didDismissWithButtonIndex \(x)") } .addDisposableTo(disposeBag) // MARK: UIBarButtonItem bbitem.rx_tap .subscribeNext { [weak self] x in self?.debug("UIBarButtonItem Tapped") } .addDisposableTo(disposeBag) // MARK: UISegmentedControl segmentedControl.rx_value .subscribeNext { [weak self] x in self?.debug("UISegmentedControl value \(x)") } .addDisposableTo(disposeBag) // MARK: UISwitch switcher.rx_value .subscribeNext { [weak self] x in self?.debug("UISwitch value \(x)") } .addDisposableTo(disposeBag) // MARK: UIButton button.rx_tap .subscribeNext { [weak self] x in self?.debug("UIButton Tapped") } .addDisposableTo(disposeBag) // MARK: UISlider slider.rx_value .subscribeNext { [weak self] x in self?.debug("UISlider value \(x)") } .addDisposableTo(disposeBag) // MARK: UIDatePicker datePicker.rx_date .subscribeNext { [weak self] x in self?.debug("UIDatePicker date \(x)") } .addDisposableTo(disposeBag) // MARK: UITextField textField.rx_text .subscribeNext { [weak self] x in self?.debug("UITextField text \(x)") self?.textField.resignFirstResponder() } .addDisposableTo(disposeBag) // MARK: UIGestureRecognizer mypan.rx_event .subscribeNext { [weak self] x in self?.debug("UIGestureRecognizer event \(x.state)") } .addDisposableTo(disposeBag) // MARK: CLLocationManager if #available(iOS 8.0, *) { manager.requestWhenInUseAuthorization() } else { // Fallback on earlier versions } manager.rx_didUpdateLocations .subscribeNext { [weak self] x in self?.debug("rx_didUpdateLocations \(x)") } .addDisposableTo(disposeBag) manager.rx_didFailWithError .subscribeNext { [weak self] x in self?.debug("rx_didFailWithError \(x)") } manager.rx_didChangeAuthorizationStatus .subscribeNext { status in print("Authorization status \(status)") } .addDisposableTo(disposeBag) manager.startUpdatingLocation() } func debug(string: String) { print(string) debugLabel.text = string } }
mit
b87b378af896fb3a767e0aa4eae7a64e
24.705628
169
0.568036
5.447706
false
false
false
false
mathiasquintero/Sweeft
Sources/Sweeft/ConstraintSatisfaction/CSP.swift
3
3410
// // CSP.swift // Pods // // Created by Mathias Quintero on 2/8/17. // // import Foundation /// Moddels a Constraint Statisfaction Problem public struct CSP<Variable: Hashable, Value> { public typealias VariableValueSpec = (name: Variable, possible: [Value]) let variables: [VariableValueSpec] let constraints: [Constraint<Variable, Value>] public init(variables: [VariableValueSpec], constraints: [Constraint<Variable, Value>]) { self.variables = variables self.constraints = constraints } } public extension CSP where Value: CSPValue { public init(variables: [Variable], constraints: [Constraint<Variable, Value>]) { self.init(variables: variables => { (name: $0, possible: Value.all) }, constraints: constraints) } public init(constraints: [Constraint<Variable, Value>]) { let variables = constraints.flatMap { $0.variables } self.init(variables: variables.noDuplicates, constraints: constraints) } } extension CSP { typealias Instance = VariableInstance<Variable, Value> func constraints(concerning variables: Variable...) -> [Constraint<Variable, Value>] { return self.constraints |> { variables.and(conjunctUsing: $0.variables.contains) } } func neighbours(of variable: Variable) -> [Variable] { let variables = constraints(concerning: variable).flatMap { $0.variables } |> { $0 != variable } return variables.noDuplicates } private func bestInstance(for instances: [Instance]) -> Instance? { let left = instances |> { !$0.isSolved } if left.count == instances.count { return left.argmin { self.neighbours(of: $0.variable).count } } else { return left.argmin { $0.values.count } } } private func removeImposibleValues(in instances: [Instance]) -> [Instance] { var solved = instances |> { $0.isSolved } let count = solved.count let instances = instances => { $0.removeImpossibleValues(regarding: instances, and: self.constraints(concerning: $0.variable)) } solved = instances |> { $0.isSolved } if count == solved.count { return instances } else { return removeImposibleValues(in: instances) } } private func solve(instances: [Instance]) -> [Instance]? { if instances.and(conjunctUsing: { $0.isSolved }) { return instances } guard let current = bestInstance(for: instances) else { return nil } let instances = instances |> { $0 != current } return current.values ==> nil ** { result, value in if let result = result { return result } let instances = self.removeImposibleValues(in: instances + .solved(variable: current.variable, value: value)) return self.solve(instances: instances) } } /// Find a Solution for the problem public func solution() -> [Variable:Value]? { let instances = variables => Instance.unsolved let solution = solve(instances: instances as [Instance]) return solution?.dictionaryWithoutOptionals { ($0.variable, $0.values.first) } } }
mit
efc580761dae98624fa5f89acca0bc30
33.1
121
0.598827
4.546667
false
false
false
false
Kartikkumargujarati/Tipster
Tipster/ViewController.swift
1
2450
// // ViewController.swift // Tipster // // Created by Kartik on 3/4/17. // Copyright © 2017 Kartik. All rights reserved. // import UIKit class ViewController: UIViewController { var bill = 0.0 var tipP = 20.0 var tip = 0.0 var total = 0.0 @IBOutlet weak var billAmount: UITextField! @IBOutlet weak var tipSlider: UISlider! @IBOutlet weak var tipAmount: UILabel! @IBOutlet weak var tipPercent: UILabel! @IBOutlet weak var totalAmount: UILabel! @IBAction func tipSliderMoved(_ sender: AnyObject) { //get Slider value tipPercent.text = "\(Int(tipSlider.value.rounded()) * 5) %" updateLabels() } override func viewDidLoad() { super.viewDidLoad() //keyboard always visible billAmount.becomeFirstResponder() //when bill amount changed billAmount.addTarget(self, action: #selector(updateBill(_:)), for: .editingChanged) updateLabels() } //function executes when bill amount changed func updateBill(_ billAmount: UITextField) { updateLabels() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //calculate and update the values, labels func updateLabels(){ //get bill value from previous session let defaultVal = UserDefaults.standard if(defaultVal.object(forKey: "prevBill") != nil){ let val = defaultVal.object(forKey: "prevTime")! if (NSDate().timeIntervalSinceReferenceDate - (val as AnyObject).timeIntervalSinceReferenceDate < 60 * 10){ billAmount.text = defaultVal.object(forKey: "prevBill") as! String! } } if billAmount.text == ""{ bill = 0.0 tipP = 0.0 }else{ bill = Double(billAmount.text!)! tipP = Double((tipSlider.value.rounded()) * 5) } tip = Double((bill * tipP)/100) total = Double(bill + tip) tipAmount.text = "$ \(tip)" totalAmount.text = "$ \(total)" } override func viewWillDisappear(_ animated: Bool) { //save the bill and current date let defaultVal = UserDefaults.standard defaultVal.setValue(bill, forKey: "prevBill") defaultVal.setValue(NSDate(), forKey: "prevTime") } }
apache-2.0
e7246c61114452608b3be955507ebb7c
28.865854
119
0.598612
4.71869
false
false
false
false
applivery/applivery-ios-sdk
AppliverySDK/Applivery/Utils/Log.swift
1
1325
// // Print.swift // AppliverySDK // // Created by Alejandro Jiménez on 12/10/15. // Copyright © 2015 Applivery S.L. All rights reserved. // import Foundation func >= (levelA: LogLevel, levelB: LogLevel) -> Bool { return levelA.rawValue >= levelB.rawValue } func log(_ log: String) { print("Applivery :: " + log) } func logInfo(_ message: String) { guard GlobalConfig.shared.logLevel >= .info else { return } log(message) } func logWarn(_ message: String, filename: NSString = #file, line: Int = #line, funcname: String = #function) { guard GlobalConfig.shared.logLevel >= .error else { return } let caller = "\(filename.lastPathComponent)(\(line)) \(funcname)" log("⚠️⚠️⚠️ WARNING: " + message) log("⚠️⚠️⚠️ ⤷ FROM CALLER: " + caller + "\n") } func logError(_ error: NSError?, filename: NSString = #file, line: Int = #line, funcname: String = #function) { guard GlobalConfig.shared.logLevel >= .error, let err = error else { return } if let code = error?.code, code == 401 || code == 402 || code == 4002 { return } let caller = "\(filename.lastPathComponent)(\(line)) \(funcname)" log("‼️‼️‼️ ERROR: " + err.localizedDescription) log("‼️‼️‼️ ⤷ FROM CALLER: " + caller) log("‼️‼️‼️ ⤷ USER INFO: \(err.userInfo)\n") }
mit
72d7d0609243e75c5f089541ef2d77ea
24.14
111
0.63564
3.206633
false
true
false
false
ngageoint/anti-piracy-iOS-app
ASAM/ListTableViewController.swift
1
1852
// // ListTableViewController.swift // ASAM // import UIKit class ListTableViewController: UITableViewController { let model = AsamModelFacade() var asams = [Asam]() let dateFormatter = DateFormatter() override func viewDidLoad() { super.viewDidLoad() navigationItem.largeTitleDisplayMode = .always navigationItem.title = "\(asams.count) ASAMs" dateFormatter.dateStyle = .short clearsSelectionOnViewWillAppear = false tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 200 } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return asams.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "asamCell", for: indexPath) as! ListViewCell let asam = asams[indexPath.row] let theDate = dateFormatter.string(from: asam.date) cell.aggressor.text = asam.hostility cell.victim.text = asam.victim cell.date.text = theDate cell.detail.text = asam.detail return cell } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue?, sender: Any?) { if (segue?.identifier == "singleListAsamDetails") { let viewController: AsamDetailsViewController = segue!.destination as! AsamDetailsViewController let path = self.tableView.indexPathForSelectedRow! viewController.asam = asams[path.row] as Asam } } }
apache-2.0
39346117db03e6fd56701b12d9e00b87
29.360656
109
0.644708
5.216901
false
false
false
false
remirobert/MNIST-machine-learning
draw-recognition/UIImagePixels.swift
1
1386
// // UIImagePixels.swift // draw-recognition // // Created by Rémi Robert on 02/06/2017. // Copyright © 2017 Rémi Robert. All rights reserved. // import UIKit extension UIImage { var pixelData: [UInt8] { let size = self.size let dataSize = size.width * size.height * 4 var pixelData = [UInt8](repeating: 0, count: Int(dataSize)) let colorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext(data: &pixelData, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 4 * Int(size.width), space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) guard let cgImage = self.cgImage else { return [] } context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) var nextPixel = 0 var greyPixels = [UInt8]() for pixel in pixelData { if nextPixel == 0 { greyPixels.append(pixel) } if nextPixel == 3 { nextPixel = 0 } else { nextPixel += 1 } } return greyPixels.map({ $0 == 255 ? 0 : 254 }) } }
mit
39adbba2c1c114bbdaeb0d7ce8d14a26
32.731707
94
0.496746
4.752577
false
false
false
false
bwhiteley/PSOperations
PSOperations/Operation.swift
3
12240
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the foundational subclass of NSOperation. */ import Foundation /** The subclass of `NSOperation` from which all other operations should be derived. This class adds both Conditions and Observers, which allow the operation to define extended readiness requirements, as well as notify many interested parties about interesting operation state changes */ public class Operation: NSOperation { // use the KVO mechanism to indicate that changes to "state" affect other properties as well class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> { return ["state"] } class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> { return ["state"] } class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> { return ["state"] } class func keyPathsForValuesAffectingIsCancelled() -> Set<NSObject> { return ["cancelledState"] } // MARK: State Management private enum State: Int, Comparable { /// The initial state of an `Operation`. case Initialized /// The `Operation` is ready to begin evaluating conditions. case Pending /// The `Operation` is evaluating conditions. case EvaluatingConditions /** The `Operation`'s conditions have all been satisfied, and it is ready to execute. */ case Ready /// The `Operation` is executing. case Executing /** Execution of the `Operation` has finished, but it has not yet notified the queue of this. */ case Finishing /// The `Operation` has finished executing. case Finished func canTransitionToState(target: State, operationIsCancelled cancelled: Bool) -> Bool { switch (self, target) { case (.Initialized, .Pending): return true case (.Pending, .EvaluatingConditions): return true case (.Pending, .Finishing) where cancelled: return true case (.Pending, .Ready) where cancelled: return true case (.EvaluatingConditions, .Ready): return true case (.Ready, .Executing): return true case (.Ready, .Finishing): return true case (.Executing, .Finishing): return true case (.Finishing, .Finished): return true default: return false } } } /** Indicates that the Operation can now begin to evaluate readiness conditions, if appropriate. */ func willEnqueue() { state = .Pending } /// Private storage for the `state` property that will be KVO observed. private var _state = State.Initialized /// A lock to guard reads and writes to the `_state` property private let stateLock = NSLock() private var state: State { get { return stateLock.withCriticalScope { _state } } set(newState) { /* It's important to note that the KVO notifications are NOT called from inside the lock. If they were, the app would deadlock, because in the middle of calling the `didChangeValueForKey()` method, the observers try to access properties like "isReady" or "isFinished". Since those methods also acquire the lock, then we'd be stuck waiting on our own lock. It's the classic definition of deadlock. */ willChangeValueForKey("state") stateLock.withCriticalScope { Void -> Void in guard _state != .Finished else { return } assert(_state.canTransitionToState(newState, operationIsCancelled: cancelled), "Performing invalid state transition.") _state = newState } didChangeValueForKey("state") } } // Here is where we extend our definition of "readiness". override public var ready: Bool { switch state { case .Initialized: // If the operation has been cancelled, "isReady" should return true return cancelled case .Pending: // If the operation has been cancelled, "isReady" should return true guard !cancelled else { state = .Ready return true } // If super isReady, conditions can be evaluated if super.ready { evaluateConditions() } // Until conditions have been evaluated, "isReady" returns false return false case .Ready: return super.ready || cancelled default: return false } } var userInitiated: Bool { get { return qualityOfService == .UserInitiated } set { assert(state < .Executing, "Cannot modify userInitiated after execution has begun.") qualityOfService = newValue ? .UserInitiated : .Default } } override public var executing: Bool { return state == .Executing } override public var finished: Bool { return state == .Finished } var _cancelled = false { willSet { willChangeValueForKey("cancelledState") } didSet { didChangeValueForKey("cancelledState") } } override public var cancelled: Bool { return _cancelled } private func evaluateConditions() { assert(state == .Pending && !cancelled, "evaluateConditions() was called out-of-order") state = .EvaluatingConditions OperationConditionEvaluator.evaluate(conditions, operation: self) { failures in if !failures.isEmpty { self.cancelWithErrors(failures) } //We must preceed to have the operation exit the queue self.state = .Ready } } // MARK: Observers and Conditions private(set) var conditions = [OperationCondition]() public func addCondition(condition: OperationCondition) { assert(state < .EvaluatingConditions, "Cannot modify conditions after execution has begun.") conditions.append(condition) } private(set) var observers = [OperationObserver]() public func addObserver(observer: OperationObserver) { assert(state < .Executing, "Cannot modify observers after execution has begun.") observers.append(observer) } override public func addDependency(operation: NSOperation) { assert(state <= .Executing, "Dependencies cannot be modified after execution has begun.") super.addDependency(operation) } // MARK: Execution and Cancellation override final public func start() { // NSOperation.start() contains important logic that shouldn't be bypassed. super.start() // If the operation has been cancelled, we still need to enter the "Finished" state. if cancelled { finish() } } override final public func main() { assert(state == .Ready, "This operation must be performed on an operation queue.") if _internalErrors.isEmpty && !cancelled { state = .Executing for observer in observers { observer.operationDidStart(self) } execute() } else { finish() } } /** `execute()` is the entry point of execution for all `Operation` subclasses. If you subclass `Operation` and wish to customize its execution, you would do so by overriding the `execute()` method. At some point, your `Operation` subclass must call one of the "finish" methods defined below; this is how you indicate that your operation has finished its execution, and that operations dependent on yours can re-evaluate their readiness state. */ public func execute() { print("\(self.dynamicType) must override `execute()`.") finish() } private var _internalErrors = [NSError]() override public func cancel() { if finished { return } _cancelled = true if state > .Ready { finish() } } public func cancelWithErrors(errors: [NSError]) { _internalErrors += errors cancel() } public func cancelWithError(error: NSError) { cancelWithErrors([error]) } public final func produceOperation(operation: NSOperation) { for observer in observers { observer.operation(self, didProduceOperation: operation) } } // MARK: Finishing /** Most operations may finish with a single error, if they have one at all. This is a convenience method to simplify calling the actual `finish()` method. This is also useful if you wish to finish with an error provided by the system frameworks. As an example, see `DownloadEarthquakesOperation` for how an error from an `NSURLSession` is passed along via the `finishWithError()` method. */ final func finishWithError(error: NSError?) { if let error = error { finish([error]) } else { finish() } } /** A private property to ensure we only notify the observers once that the operation has finished. */ private var hasFinishedAlready = false public final func finish(errors: [NSError] = []) { if !hasFinishedAlready { hasFinishedAlready = true state = .Finishing let combinedErrors = _internalErrors + errors finished(combinedErrors) for observer in observers { observer.operationDidFinish(self, errors: combinedErrors) } state = .Finished } } /** Subclasses may override `finished(_:)` if they wish to react to the operation finishing with errors. For example, the `LoadModelOperation` implements this method to potentially inform the user about an error when trying to bring up the Core Data stack. */ public func finished(errors: [NSError]) { // No op. } override public func waitUntilFinished() { /* Waiting on operations is almost NEVER the right thing to do. It is usually superior to use proper locking constructs, such as `dispatch_semaphore_t` or `dispatch_group_notify`, or even `NSLocking` objects. Many developers use waiting when they should instead be chaining discrete operations together using dependencies. To reinforce this idea, invoking `waitUntilFinished()` will crash your app, as incentive for you to find a more appropriate way to express the behavior you're wishing to create. */ fatalError("Waiting on operations is an anti-pattern. Remove this ONLY if you're absolutely sure there is No Other Way™.") } } // Simple operator functions to simplify the assertions used above. private func <(lhs: Operation.State, rhs: Operation.State) -> Bool { return lhs.rawValue < rhs.rawValue } private func ==(lhs: Operation.State, rhs: Operation.State) -> Bool { return lhs.rawValue == rhs.rawValue }
mit
291ec8660674c1b39c7b6fa8c1b3cef7
30.455013
134
0.578539
5.602564
false
false
false
false
sharath-cliqz/browser-ios
Client/Frontend/Menu/AppMenuToolbarItem.swift
2
802
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation struct AppMenuToolbarItem: MenuToolbarItem { fileprivate let iconName: String let title: String let action: MenuAction let secondaryAction: MenuAction? fileprivate var icon: UIImage? { return UIImage(named: iconName) } func iconForState(_ appState: AppState) -> UIImage? { return icon } init(title: String, action: MenuAction, secondaryAction: MenuAction? = nil, icon: String) { self.title = title self.action = action self.secondaryAction = secondaryAction self.iconName = icon } }
mpl-2.0
4fb2eaca654e7983524a876b2069ae9c
26.655172
95
0.670823
4.430939
false
false
false
false
klundberg/swift-corelibs-foundation
Foundation/NSMeasurementFormatter.swift
1
3448
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // extension MeasurementFormatter { public struct UnitOptions : OptionSet { public private(set) var rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let providedUnit = UnitOptions(rawValue: 1 << 0) public static let naturalScale = UnitOptions(rawValue: 1 << 1) public static let temperatureWithoutUnit = UnitOptions(rawValue: 1 << 2) } } public class MeasurementFormatter : Formatter, NSSecureCoding { /* This property can be set to ensure that the formatter behaves in a way the developer expects, even if it is not standard according to the preferences of the user's locale. If not specified, unitOptions defaults to localizing according to the preferences of the locale. Ex: By default, if unitOptions is set to the empty set, the formatter will do the following: - kilocalories may be formatted as "C" instead of "kcal" depending on the locale. - kilometersPerHour may be formatted as "miles per hour" for US and UK locales but "kilometers per hour" for other locales. However, if NSMeasurementFormatterUnitOptionsProvidedUnit is set, the formatter will do the following: - kilocalories would be formatted as "kcal" in the language of the locale, even if the locale prefers "C". - kilometersPerHour would be formatted as "kilometers per hour" for US and UK locales even though the preference is for "miles per hour." Note that NSMeasurementFormatter will handle converting measurement objects to the preferred units in a particular locale. For instance, if provided a measurement object in kilometers and the set locale is en_US, the formatter will implicitly convert the measurement object to miles and return the formatted string as the equivalent measurement in miles. */ public var unitOptions: MeasurementFormatter.UnitOptions = [] /* If not specified, unitStyle is set to NSFormattingUnitStyleMedium. */ public var unitStyle: Formatter.UnitStyle /* If not specified, locale is set to the user's current locale. */ /*@NSCopying*/ public var locale: Locale! /* If not specified, the number formatter is set up with NSNumberFormatterDecimalStyle. */ public var numberFormatter: NumberFormatter! public func string(from measurement: Measurement<Unit>) -> String { NSUnimplemented() } /* @param An NSUnit @return A formatted string representing the localized form of the unit without a value attached to it. This method will return [unit symbol] if the provided unit cannot be localized. */ public func string(from unit: Unit) -> String { NSUnimplemented() } public override init() { NSUnimplemented() } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public override func encode(with aCoder: NSCoder) { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } }
apache-2.0
4054613bc278ad19b48d81dd3d3151a7
42.64557
360
0.706206
5.040936
false
false
false
false
CocoaPods/Xcodeproj
spec/fixtures/CommonBuildSettings/Project/Swift_iOS_Native/AppDelegate.swift
2
3178
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
a43613da7d5a0128d4a59e8b1430cbaa
58.962264
285
0.766205
6.512295
false
false
false
false
accepton/accepton-apple
Pod/Classes/AcceptOnUIMachine/Drivers/CreditCard/Braintree.swift
1
1747
import UIKit import BraintreePrivate extension BTCard { convenience init(_ creditCardParams: AcceptOnAPICreditCardParams) { self.init() self.number = creditCardParams.number self.expirationMonth = creditCardParams.expMonth ?? "" self.expirationYear = creditCardParams.expYear } } class AcceptOnUIMachineCreditCardBraintreePlugin: AcceptOnUIMachineCreditCardDriverPlugin { override var name: String { return "braintree" } override func beginTransactionWithFormOptions(formOptions: AcceptOnUIMachineFormOptions) { if let nonce = formOptions.paymentMethods.braintreeRawEncodedClientToken { guard let api = BTAPIClient(authorization: nonce) else { self.delegate.creditCardPlugin(self, didFailWithMessage: "The Braintree client could not be configured") return } let cardClient = BTCardClient(APIClient: api) cardClient.tokenizeCard(BTCard(formOptions.creditCardParams!)) { nonce, err in if let err = err { self.delegate.creditCardPlugin(self, didFailWithMessage: err.localizedDescription) return } guard let tokenId = nonce?.nonce else { self.delegate.creditCardPlugin(self, didFailWithMessage: "Could not decode response from Braintree") return } self.delegate.creditCardPlugin(self, didSucceedWithNonce: tokenId) } } else { self.delegate.creditCardPlugin(self, didFailWithMessage: "The Braintree publishable key could not be retrieved") } } }
mit
7f822fb94308301be862dd7d27d78f55
39.627907
124
0.633085
5.635484
false
false
false
false
tapz/MWPhotoBrowserSwift
Pod/Classes/ZoomingScrollView.swift
1
16324
// // ZoomingScrollView.swift // Pods // // Created by Tapani Saarinen on 06/09/15. // // import UIKit import DACircularProgress public class ZoomingScrollView: UIScrollView, UIScrollViewDelegate, TapDetectingImageViewDelegate, TapDetectingViewDelegate { public var index = 0 public var mwPhoto: Photo? public weak var captionView: CaptionView? public weak var selectedButton: UIButton? public weak var playButton: UIButton? private weak var photoBrowser: PhotoBrowser! private var tapView = TapDetectingView(frame: CGRectZero) // for background taps private var photoImageView = TapDetectingImageView(frame: CGRectZero) private var loadingIndicator = DACircularProgressView(frame: CGRectMake(140.0, 30.0, 40.0, 40.0)) private var loadingError: UIImageView? public init(photoBrowser: PhotoBrowser) { super.init(frame: CGRectZero) // Setup index = Int.max self.photoBrowser = photoBrowser // Tap view for background tapView = TapDetectingView(frame: bounds) tapView.tapDelegate = self tapView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] tapView.backgroundColor = UIColor.whiteColor() addSubview(tapView) // Image view photoImageView.tapDelegate = self photoImageView.contentMode = UIViewContentMode.Center addSubview(photoImageView) // Loading indicator loadingIndicator.userInteractionEnabled = false loadingIndicator.thicknessRatio = 0.1 loadingIndicator.roundedCorners = 0 loadingIndicator.autoresizingMask = [.FlexibleLeftMargin, .FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleRightMargin] addSubview(loadingIndicator) // Listen progress notifications NSNotificationCenter.defaultCenter().addObserver( self, selector: Selector("setProgressFromNotification:"), name: MWPHOTO_PROGRESS_NOTIFICATION, object: nil) // Setup backgroundColor = UIColor.whiteColor() delegate = self showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false decelerationRate = UIScrollViewDecelerationRateFast autoresizingMask = [.FlexibleWidth, .FlexibleHeight] } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func prepareForReuse() { hideImageFailure() photo = nil captionView = nil selectedButton = nil playButton = nil photoImageView.hidden = false photoImageView.image = nil index = Int.max } func displayingVideo() -> Bool { if let p = photo { return p.isVideo } return false } public override var backgroundColor: UIColor? { set(color) { tapView.backgroundColor = color super.backgroundColor = color } get { return super.backgroundColor } } var imageHidden: Bool { set(hidden) { photoImageView.hidden = hidden } get { return photoImageView.hidden } } //MARK: - Image var photo: Photo? { set(p) { // Cancel any loading on old photo if mwPhoto != nil && p == nil { mwPhoto!.cancelAnyLoading() } mwPhoto = p if photoBrowser.imageForPhoto(mwPhoto) != nil { self.displayImage() } else { // Will be loading so show loading self.showLoadingIndicator() } } get { return mwPhoto } } // Get and display image func displayImage() { if mwPhoto != nil && photoImageView.image == nil { // Reset maximumZoomScale = 1.0 minimumZoomScale = 1.0 zoomScale = 1.0 contentSize = CGSizeMake(0.0, 0.0) // Get image from browser as it handles ordering of fetching if let img = photoBrowser.imageForPhoto(photo) { // Hide indicator hideLoadingIndicator() // Set image photoImageView.image = img photoImageView.hidden = false // Setup photo frame var photoImageViewFrame = CGRectZero photoImageViewFrame.origin = CGPointZero photoImageViewFrame.size = img.size photoImageView.frame = photoImageViewFrame contentSize = photoImageViewFrame.size // Set zoom to minimum zoom setMaxMinZoomScalesForCurrentBounds() } else { // Show image failure displayImageFailure() } setNeedsLayout() } } // Image failed so just show grey! func displayImageFailure() { hideLoadingIndicator() photoImageView.image = nil // Show if image is not empty if let p = photo { if p.emptyImage { if nil == loadingError { loadingError = UIImageView() loadingError!.image = UIImage.imageForResourcePath( "MWPhotoBrowserSwift.bundle/ImageError", ofType: "png", inBundle: NSBundle(forClass: ZoomingScrollView.self)) loadingError!.userInteractionEnabled = false loadingError!.autoresizingMask = [.FlexibleLeftMargin, .FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleRightMargin] loadingError!.sizeToFit() addSubview(loadingError!) } loadingError!.frame = CGRectMake( floorcgf((bounds.size.width - loadingError!.frame.size.width) / 2.0), floorcgf((bounds.size.height - loadingError!.frame.size.height) / 2.0), loadingError!.frame.size.width, loadingError!.frame.size.height) } } } private func hideImageFailure() { if let e = loadingError { e.removeFromSuperview() loadingError = nil } } //MARK: - Loading Progress public func setProgressFromNotification(notification: NSNotification) { dispatch_async(dispatch_get_main_queue()) { let dict = notification.object as! [String : AnyObject] if let photoWithProgress = dict["photo"] as? Photo, p = self.photo where photoWithProgress.equals(p) { if let progress = dict["progress"] as? Float { self.loadingIndicator.progress = CGFloat(max(min(1.0, progress), 0.0)) } } } } private func hideLoadingIndicator() { loadingIndicator.hidden = true } private func showLoadingIndicator() { zoomScale = 0.1 minimumZoomScale = 0.1 maximumZoomScale = 0.1 loadingIndicator.progress = 0.0 loadingIndicator.hidden = false hideImageFailure() } //MARK: - Setup private func initialZoomScaleWithMinScale() -> CGFloat { var zoomScale = minimumZoomScale if let pb = photoBrowser where pb.zoomPhotosToFill { // Zoom image to fill if the aspect ratios are fairly similar let boundsSize = self.bounds.size let imageSize = photoImageView.image != nil ? photoImageView.image!.size : CGSizeMake(0.0, 0.0) let boundsAR = boundsSize.width / boundsSize.height let imageAR = imageSize.width / imageSize.height let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise // Zooms standard portrait images on a 3.5in screen but not on a 4in screen. if (abs(boundsAR - imageAR) < 0.17) { zoomScale = max(xScale, yScale) // Ensure we don't zoom in or out too far, just in case zoomScale = min(max(minimumZoomScale, zoomScale), maximumZoomScale) } } return zoomScale } func setMaxMinZoomScalesForCurrentBounds() { // Reset maximumZoomScale = 1.0 minimumZoomScale = 1.0 zoomScale = 1.0 // Bail if no image if photoImageView.image == nil { return } // Reset position photoImageView.frame = CGRectMake(0, 0, photoImageView.frame.size.width, photoImageView.frame.size.height) // Sizes let boundsSize = self.bounds.size let imageSize = photoImageView.image!.size // Calculate Min let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise var minScale = min(xScale, yScale) // use minimum of these to allow the image to become fully visible // Calculate Max var maxScale = 3.0 if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad { // Let them go a bit bigger on a bigger screen! maxScale = 4.0 } // Image is smaller than screen so no zooming! if xScale >= 1.0 && yScale >= 1.0 { minScale = 1.0 } // Set min/max zoom maximumZoomScale = CGFloat(maxScale) minimumZoomScale = CGFloat(minScale) // Initial zoom zoomScale = initialZoomScaleWithMinScale() // If we're zooming to fill then centralise if zoomScale != minScale { // Centralise contentOffset = CGPointMake((imageSize.width * zoomScale - boundsSize.width) / 2.0, (imageSize.height * zoomScale - boundsSize.height) / 2.0) } // Disable scrolling initially until the first pinch to fix issues with swiping on an initally zoomed in photo scrollEnabled = false // If it's a video then disable zooming if displayingVideo() { maximumZoomScale = zoomScale minimumZoomScale = zoomScale } // Layout setNeedsLayout() } //MARK: - Layout public override func layoutSubviews() { // Update tap view frame tapView.frame = bounds // Position indicators (centre does not seem to work!) if !loadingIndicator.hidden { loadingIndicator.frame = CGRectMake( floorcgf((bounds.size.width - loadingIndicator.frame.size.width) / 2.0), floorcgf((bounds.size.height - loadingIndicator.frame.size.height) / 2.0), loadingIndicator.frame.size.width, loadingIndicator.frame.size.height) } if let le = loadingError { le.frame = CGRectMake( floorcgf((bounds.size.width - le.frame.size.width) / 2.0), floorcgf((bounds.size.height - le.frame.size.height) / 2.0), le.frame.size.width, le.frame.size.height) } // Super super.layoutSubviews() // Center the image as it becomes smaller than the size of the screen let boundsSize = bounds.size var frameToCenter = photoImageView.frame // Horizontally if frameToCenter.size.width < boundsSize.width { frameToCenter.origin.x = floorcgf((boundsSize.width - frameToCenter.size.width) / 2.0) } else { frameToCenter.origin.x = 0.0 } // Vertically if frameToCenter.size.height < boundsSize.height { frameToCenter.origin.y = floorcgf((boundsSize.height - frameToCenter.size.height) / 2.0) } else { frameToCenter.origin.y = 0.0 } // Center if !CGRectEqualToRect(photoImageView.frame, frameToCenter) { photoImageView.frame = frameToCenter } } //MARK: - UIScrollViewDelegate public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return photoImageView } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { photoBrowser.cancelControlHiding() } public func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) { scrollEnabled = true // reset photoBrowser.cancelControlHiding() } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { photoBrowser.hideControlsAfterDelay() } public func scrollViewDidZoom(scrollView: UIScrollView) { setNeedsLayout() layoutIfNeeded() } //MARK: - Tap Detection private func handleSingleTap(touchPoint: CGPoint) { dispatch_after( dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { self.photoBrowser.toggleControls() } } private func handleDoubleTap(touchPoint: CGPoint) { // Dont double tap to zoom if showing a video if displayingVideo() { return } // Cancel any single tap handling NSObject.cancelPreviousPerformRequestsWithTarget(photoBrowser) // Zoom if zoomScale != minimumZoomScale && zoomScale != initialZoomScaleWithMinScale() { // Zoom out setZoomScale(minimumZoomScale, animated: true) } else { // Zoom in to twice the size let newZoomScale = ((maximumZoomScale + minimumZoomScale) / 2.0) let xsize = bounds.size.width / newZoomScale let ysize = bounds.size.height / newZoomScale zoomToRect(CGRectMake(touchPoint.x - xsize / 2.0, touchPoint.y - ysize / 2.0, xsize, ysize), animated: true) } // Delay controls photoBrowser.hideControlsAfterDelay() } // Image View public func singleTapDetectedInImageView(view: UIImageView, touch: UITouch) { handleSingleTap(touch.locationInView(view)) } public func doubleTapDetectedInImageView(view: UIImageView, touch: UITouch) { handleDoubleTap(touch.locationInView(view)) } public func tripleTapDetectedInImageView(view: UIImageView, touch: UITouch) { } // Background View public func singleTapDetectedInView(view: UIView, touch: UITouch) { // Translate touch location to image view location var touchX = touch.locationInView(view).x var touchY = touch.locationInView(view).y touchX *= 1.0 / self.zoomScale touchY *= 1.0 / self.zoomScale touchX += self.contentOffset.x touchY += self.contentOffset.y handleSingleTap(CGPointMake(touchX, touchY)) } public func doubleTapDetectedInView(view: UIView, touch: UITouch) { // Translate touch location to image view location var touchX = touch.locationInView(view).x var touchY = touch.locationInView(view).y touchX *= 1.0 / self.zoomScale touchY *= 1.0 / self.zoomScale touchX += self.contentOffset.x touchY += self.contentOffset.y handleDoubleTap(CGPointMake(touchX, touchY)) } public func tripleTapDetectedInView(view: UIView, touch: UITouch) { } }
mit
8192b55fb90003b524d712d864030fe5
32.519507
125
0.580005
5.63285
false
false
false
false
thombles/Flyweight
Flyweight/Data/DataEnums.swift
1
1034
// Flyweight - iOS client for GNU social // Copyright 2017 Thomas Karpiniec // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation @objc public enum GSTimelineType: Int32 { case Home = 1 case User = 2 case Public = 3 case KnownNetwork = 4 case Mentions = 5 // basic mentions_timeline implementation, notices only case Favourites = 6 case Search = 7 case Tag = 8 case Group = 9 case Notifications = 10 // a fuller featured stream from Qvitter case Conversation = 11 }
apache-2.0
c043e98b5b52dd9f5b62d286e1a11fb1
33.466667
77
0.716634
4.255144
false
false
false
false
devpunk/cartesian
cartesian/View/Main/Parent/VParent.swift
1
9970
import UIKit class VParent:UIView { private(set) weak var viewBar:VParentBar! private(set) weak var panRecognizer:UIPanGestureRecognizer! private weak var controller:CParent! private weak var layoutBarTop:NSLayoutConstraint! private var panningX:CGFloat? private let kAnimationDuration:TimeInterval = 0.4 private let kBarHeight:CGFloat = 70 private let kMaxXPanning:CGFloat = 60 private let kMaxXDelta:CGFloat = 210 private let kMinXDelta:CGFloat = 30 convenience init(controller:CParent) { self.init() clipsToBounds = true backgroundColor = UIColor.white self.controller = controller let viewBar:VParentBar = VParentBar(controller:controller) self.viewBar = viewBar addSubview(viewBar) NSLayoutConstraint.height( view:viewBar, constant:kBarHeight) NSLayoutConstraint.topToTop( view:viewBar, toView:self) NSLayoutConstraint.width( view:viewBar, toView:self) let panRecognizer:UIPanGestureRecognizer = UIPanGestureRecognizer( target:self, action:#selector(actionPanRecognized(sender:))) panRecognizer.isEnabled = false self.panRecognizer = panRecognizer addGestureRecognizer(panRecognizer) } //MARK: actions func actionPanRecognized(sender panGesture:UIPanGestureRecognizer) { let location:CGPoint = panGesture.location( in:self) let xPos:CGFloat = location.x switch panGesture.state { case UIGestureRecognizerState.began, UIGestureRecognizerState.possible: if xPos < kMaxXPanning { self.panningX = xPos } break case UIGestureRecognizerState.changed: if let panningX:CGFloat = self.panningX { var deltaX:CGFloat = xPos - panningX if deltaX > kMaxXDelta { panRecognizer.isEnabled = false } else { if deltaX < 0 { deltaX = 0 } guard let topView:VView = subviews.last as? VView else { return } topView.layoutLeft.constant = deltaX } } break case UIGestureRecognizerState.cancelled, UIGestureRecognizerState.ended, UIGestureRecognizerState.failed: if let panningX:CGFloat = self.panningX { let deltaX:CGFloat = xPos - panningX if deltaX > kMinXDelta { gesturePop() } else { gestureRestore() } } panningX = nil break } } //MARK: private private func gesturePop() { controller.pop(horizontal:CParent.TransitionHorizontal.fromRight) } private func gestureRestore() { guard let topView:VView = subviews.last as? VView else { return } topView.layoutLeft.constant = 0 UIView.animate(withDuration:kAnimationDuration) { self.layoutIfNeeded() } } //MARK: public func scrollDidScroll(offsetY:CGFloat) { let barTopConstant:CGFloat if offsetY > 0 { barTopConstant = offsetY } else { barTopConstant = 0 } layoutBarTop.constant = -barTopConstant } func mainView(view:VView) { insertSubview(view, belowSubview:viewBar) view.layoutTop = NSLayoutConstraint.topToTop( view:view, toView:self) view.layoutBottom = NSLayoutConstraint.bottomToBottom( view:view, toView:self) view.layoutLeft = NSLayoutConstraint.leftToLeft( view:view, toView:self) view.layoutRight = NSLayoutConstraint.rightToRight( view:view, toView:self) } func slide( currentView:VView, newView:VView, left:CGFloat, completion:@escaping(() -> ())) { insertSubview(newView, belowSubview:viewBar) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self, constant:-left) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self, constant:-left) layoutIfNeeded() currentView.layoutRight.constant = left currentView.layoutLeft.constant = left newView.layoutRight.constant = 0 newView.layoutLeft.constant = 0 UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() }) { (done:Bool) in currentView.removeFromSuperview() completion() } } func push( newView:VView, left:CGFloat, top:CGFloat, background:Bool, completion:@escaping(() -> ())) { if background { let pushBackground:VParentPushBackground = VParentPushBackground() newView.pushBackground = pushBackground addSubview(pushBackground) NSLayoutConstraint.equals( view:pushBackground, toView:self) } addSubview(newView) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self, constant:top) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self, constant:top) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self, constant:left) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self, constant:left) layoutIfNeeded() if top >= 0 { newView.layoutTop.constant = 0 newView.layoutBottom.constant = 0 } else { newView.layoutBottom.constant = 0 newView.layoutTop.constant = 0 } if left >= 0 { newView.layoutLeft.constant = 0 newView.layoutRight.constant = 0 } else { newView.layoutRight.constant = 0 newView.layoutLeft.constant = 0 } UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() newView.pushBackground?.alpha = 1 }) { (done:Bool) in completion() } } func animateOver( newView:VView, completion:@escaping(() -> ())) { newView.alpha = 0 addSubview(newView) newView.layoutTop = NSLayoutConstraint.topToTop( view:newView, toView:self) newView.layoutBottom = NSLayoutConstraint.bottomToBottom( view:newView, toView:self) newView.layoutLeft = NSLayoutConstraint.leftToLeft( view:newView, toView:self) newView.layoutRight = NSLayoutConstraint.rightToRight( view:newView, toView:self) UIView.animate( withDuration:kAnimationDuration, animations: { [weak newView] in newView?.alpha = 1 }) { (done:Bool) in completion() } } func pop( currentView:VView, left:CGFloat, top:CGFloat, completion:@escaping(() -> ())) { currentView.layoutTop.constant = top currentView.layoutBottom.constant = top currentView.layoutRight.constant = left currentView.layoutLeft.constant = left UIView.animate( withDuration:kAnimationDuration, animations: { self.layoutIfNeeded() currentView.pushBackground?.alpha = 0 }) { (done:Bool) in currentView.pushBackground?.removeFromSuperview() currentView.removeFromSuperview() completion() } } func dismissAnimateOver( currentView:VView, completion:@escaping(() -> ())) { UIView.animate( withDuration:kAnimationDuration, animations: { [weak currentView] in currentView?.alpha = 0 }) { [weak currentView] (done:Bool) in currentView?.removeFromSuperview() completion() } } }
mit
690e52ba9c36a347e474dd76188e4b16
25.375661
78
0.500702
6.322131
false
false
false
false
magicien/GLTFSceneKit
Sources/GLTFSceneKit/GLTFUnarchiver.swift
1
73997
// // GLTFUnarhiver.swift // GLTFSceneKit // // Created by magicien on 2017/08/17. // Copyright © 2017 DarkHorse. All rights reserved. // import SceneKit import SpriteKit import QuartzCore import CoreGraphics let glbMagic = 0x46546C67 // "glTF" let chunkTypeJSON = 0x4E4F534A // "JSON" let chunkTypeBIN = 0x004E4942 // "BIN" let bundle = Bundle.module_workaround public class GLTFUnarchiver { private var directoryPath: URL? = nil private var json: GLTFGlTF! = nil private var bin: Data? internal var scene: SCNScene? internal var scenes: [SCNScene?] = [] internal var cameras: [SCNCamera?] = [] internal var nodes: [SCNNode?] = [] internal var skins: [SCNSkinner?] = [] internal var animationChannels: [[CAAnimation?]?] = [] internal var animationSamplers: [[CAAnimation?]?] = [] internal var meshes: [SCNNode?] = [] internal var accessors: [Any?] = [] internal var durations: [CFTimeInterval?] = [] internal var bufferViews: [Data?] = [] internal var buffers: [Data?] = [] internal var materials: [SCNMaterial?] = [] internal var textures: [SCNMaterialProperty?] = [] internal var images: [Image?] = [] internal var maxAnimationDuration: CFTimeInterval = 0.0 #if !os(watchOS) private var workingAnimationGroup: CAAnimationGroup! = nil #endif convenience public init(path: String, extensions: [String:Codable.Type]? = nil) throws { var url: URL? if let mainPath = Bundle.main.path(forResource: path, ofType: "") { url = URL(fileURLWithPath: mainPath) } else { url = URL(fileURLWithPath: path) } guard let _url = url else { throw URLError(.fileDoesNotExist) } try self.init(url: _url, extensions: extensions) } convenience public init(url: URL, extensions: [String:Codable.Type]? = nil) throws { let data = try Data(contentsOf: url) try self.init(data: data, extensions: extensions) self.directoryPath = url.deletingLastPathComponent() } public init(data: Data, extensions: [String:Codable.Type]? = nil) throws { let decoder = JSONDecoder() var _extensions = extensionList extensions?.forEach { (ext) in _extensions[ext.key] = ext.value } decoder.userInfo[GLTFExtensionCodingUserInfoKey] = _extensions let _extras = [ "TargetNames": GLTFExtrasTargetNames.self ] decoder.userInfo[GLTFExtrasCodingUserInfoKey] = _extras var jsonData = data let magic: UInt32 = data.subdata(in: 0..<4).withUnsafeBytes { $0.pointee } if magic == glbMagic { let version: UInt32 = data.subdata(in: 4..<8).withUnsafeBytes { $0.pointee } if version != 2 { throw GLTFUnarchiveError.NotSupported("version \(version) is not supported") } let length: UInt32 = data.subdata(in: 8..<12).withUnsafeBytes { $0.pointee } let chunk0Length: UInt32 = data.subdata(in: 12..<16).withUnsafeBytes { $0.pointee } let chunk0Type: UInt32 = data.subdata(in: 16..<20).withUnsafeBytes { $0.pointee } if chunk0Type != chunkTypeJSON { throw GLTFUnarchiveError.NotSupported("chunkType \(chunk0Type) is not supported") } let chunk0EndPos = 20 + Int(chunk0Length) jsonData = data.subdata(in: 20..<chunk0EndPos) if length > chunk0EndPos { let chunk1Length: UInt32 = data.subdata(in: chunk0EndPos..<chunk0EndPos+4).withUnsafeBytes { $0.pointee } let chunk1Type: UInt32 = data.subdata(in: chunk0EndPos+4..<chunk0EndPos+8).withUnsafeBytes { $0.pointee } if chunk1Type != chunkTypeBIN { throw GLTFUnarchiveError.NotSupported("chunkType \(chunk1Type) is not supported") } let chunk1EndPos = chunk0EndPos + 8 + Int(chunk1Length) self.bin = data.subdata(in: chunk0EndPos+8..<chunk1EndPos) } } // just throw the error to the user self.json = try decoder.decode(GLTFGlTF.self, from: jsonData) // Errors can be: // DecodingError.keyNotFound(let key, let context) // DecodingError.typeMismatch(let type, let context) // DecodingError.valueNotFound(let type, let context) self.initArrays() } private func initArrays() { if let scenes = self.json.scenes { self.scenes = [SCNScene?](repeating: nil, count: scenes.count) } if let cameras = self.json.cameras { self.cameras = [SCNCamera?](repeating: nil, count: cameras.count) } if let nodes = self.json.nodes { self.nodes = [SCNNode?](repeating: nil, count: nodes.count) } if let skins = self.json.skins { self.skins = [SCNSkinner?](repeating: nil, count: skins.count) } if let animations = self.json.animations { //if #available(OSX 10.13, *) { // self.animationChannels = [[SCNAnimation?]?](repeating: nil, count: animations.count) self.animationChannels = [[CAAnimation?]?](repeating: nil, count: animations.count) self.animationSamplers = [[CAAnimation?]?](repeating: nil, count: animations.count) //} else { // print("GLTFAnimation is not supported for this OS version.") //} } if let meshes = self.json.meshes { self.meshes = [SCNNode?](repeating: nil, count: meshes.count) } if let accessors = self.json.accessors { self.accessors = [Any?](repeating: nil, count: accessors.count) self.durations = [CFTimeInterval?](repeating: nil, count: accessors.count) } if let bufferViews = self.json.bufferViews { self.bufferViews = [Data?](repeating: nil, count: bufferViews.count) } if let buffers = self.json.buffers { self.buffers = [Data?](repeating: nil, count: buffers.count) } if let materials = self.json.materials { self.materials = [SCNMaterial?](repeating: nil, count: materials.count) } if let textures = self.json.textures { self.textures = [SCNMaterialProperty?](repeating: nil, count: textures.count) } if let images = self.json.images { self.images = [Image?](repeating: nil, count: images.count) } } private func getBase64Str(from str: String) -> String? { guard str.starts(with: "data:") else { return nil } let mark = ";base64," guard str.contains(mark) else { return nil } guard let base64Str = str.components(separatedBy: mark).last else { return nil } return base64Str } private func calcPrimitiveCount(ofCount count: Int, primitiveType: SCNGeometryPrimitiveType) -> Int { switch primitiveType { case .line: return count / 2 case .point: return count case .polygon: // Is it correct? return count - 2 case .triangles: return count / 3 case .triangleStrip: return count - 2 } } private func loadCamera(index: Int) throws -> SCNCamera { guard index < self.cameras.count else { throw GLTFUnarchiveError.DataInconsistent("loadCamera: out of index: \(index) < \(self.cameras.count)") } if let camera = self.cameras[index] { return camera } guard let cameras = self.json.cameras else { throw GLTFUnarchiveError.DataInconsistent("loadCamera: cameras is not defined") } let glCamera = cameras[index] let camera = SCNCamera() if let name = glCamera.name { camera.name = name } switch glCamera.type { case "perspective": camera.usesOrthographicProjection = false guard let perspective = glCamera.perspective else { throw GLTFUnarchiveError.DataInconsistent("loadCamera: perspective is not defined") } // SceneKit automatically calculates the viewing angle in the other direction to match // the aspect ratio of the view displaying the scene camera.fieldOfView = CGFloat(perspective.yfov * 180.0 / Float.pi) camera.zNear = Double(perspective.znear) camera.zFar = Double(perspective.zfar ?? Float.infinity) perspective.didLoad(by: camera, unarchiver: self) case "orthographic": camera.usesOrthographicProjection = true guard let orthographic = glCamera.orthographic else { throw GLTFUnarchiveError.DataInconsistent("loadCamera: orthographic is not defined") } // TODO: use xmag camera.orthographicScale = Double(orthographic.ymag) camera.zNear = Double(orthographic.znear) camera.zFar = Double(orthographic.zfar) orthographic.didLoad(by: camera, unarchiver: self) default: throw GLTFUnarchiveError.NotSupported("loadCamera: type \(glCamera.type) is not supported") } glCamera.didLoad(by: camera, unarchiver: self) return camera } private func loadBuffer(index: Int) throws -> Data { guard index < self.buffers.count else { throw GLTFUnarchiveError.DataInconsistent("loadBuffer: out of index: \(index) < \(self.buffers.count)") } if let buffer = self.buffers[index] { return buffer } guard let buffers = self.json.buffers else { throw GLTFUnarchiveError.DataInconsistent("loadBufferView: buffers is not defined") } let glBuffer = buffers[index] var _buffer: Data? if let uri = glBuffer.uri { if let base64Str = self.getBase64Str(from: uri) { _buffer = Data(base64Encoded: base64Str) } else { let url = URL(fileURLWithPath: uri, relativeTo: self.directoryPath) _buffer = try Data(contentsOf: url) } } else { _buffer = self.bin } guard let buffer = _buffer else { throw GLTFUnarchiveError.Unknown("loadBufferView: buffer \(index) load error") } guard buffer.count >= glBuffer.byteLength else { throw GLTFUnarchiveError.DataInconsistent("loadBuffer: buffer.count < byteLength: \(buffer.count) < \(glBuffer.byteLength)") } self.buffers[index] = buffer glBuffer.didLoad(by: buffer, unarchiver: self) return buffer } private func loadBufferView(index: Int, expectedTarget: Int? = nil) throws -> Data { guard index < self.bufferViews.count else { throw GLTFUnarchiveError.DataInconsistent("loadBufferView: out of index: \(index) < \(self.bufferViews.count)") } if let bufferView = self.bufferViews[index] { return bufferView } guard let bufferViews = self.json.bufferViews else { throw GLTFUnarchiveError.DataInconsistent("loadBufferView: bufferViews is not defined") } let glBufferView = bufferViews[index] if let expectedTarget = expectedTarget { if let target = glBufferView.target { guard expectedTarget == target else { throw GLTFUnarchiveError.DataInconsistent("loadBufferView: index \(index): target inconsistent") } } } let buffer = try self.loadBuffer(index: glBufferView.buffer) let bufferView = buffer.subdata(in: glBufferView.byteOffset..<glBufferView.byteOffset + glBufferView.byteLength) self.bufferViews[index] = bufferView glBufferView.didLoad(by: bufferView, unarchiver: self) return bufferView } private func iterateBufferView(index: Int, offset: Int, stride: Int, count: Int, block: @escaping (UnsafeRawPointer) -> Void) throws { guard count > 0 else { return } let bufferView = try self.loadBufferView(index: index) let glBufferView = self.json.bufferViews![index] var byteStride = stride if let glByteStride = glBufferView.byteStride { byteStride = glByteStride } guard offset + byteStride * count <= glBufferView.byteLength else { throw GLTFUnarchiveError.DataInconsistent("iterateBufferView: offset (\(offset)) + byteStride (\(byteStride)) * count (\(count)) shoule be equal or less than byteLength (\(glBufferView.byteLength)))") } bufferView.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in var p = pointer.advanced(by: offset) for _ in 0..<count { block(UnsafeRawPointer(p)) p = p.advanced(by: byteStride) } } } private func getDataStride(ofBufferViewIndex index: Int) throws -> Int? { guard let bufferViews = self.json.bufferViews else { throw GLTFUnarchiveError.DataInconsistent("getDataStride: bufferViews is not defined") } guard index < bufferViews.count else { throw GLTFUnarchiveError.DataInconsistent("getDataStride: out of index: \(index) < \(bufferViews.count)") } // it could be nil because it is not required. guard let stride = bufferViews[index].byteStride else { return nil } return stride } private func createIndexData(_ data: Data, offset: Int, size: Int, stride: Int, count: Int) -> Data { let dataSize = size * count if stride == size { if offset == 0 { return data } return data.subdata(in: offset..<offset + dataSize) } var indexData = Data(capacity: dataSize) data.withUnsafeBytes { (s: UnsafePointer<UInt8>) in indexData.withUnsafeMutableBytes { (d: UnsafeMutablePointer<UInt8>) in let srcStep = stride - size var srcPos = offset var dstPos = 0 for _ in 0..<count { for _ in 0..<size { d[dstPos] = s[srcPos] srcPos += 1 dstPos += 1 } srcPos += srcStep } } } return indexData } private func loadVertexAccessor(index: Int, semantic: SCNGeometrySource.Semantic) throws -> SCNGeometrySource { guard index < self.accessors.count else { throw GLTFUnarchiveError.DataInconsistent("loadVertexAccessor: out of index: \(index) < \(self.accessors.count)") } if let accessor = self.accessors[index] as? SCNGeometrySource { return accessor } if self.accessors[index] != nil { throw GLTFUnarchiveError.DataInconsistent("loadVertexAccessor: the accessor \(index) is not SCNGeometrySource") } guard let accessors = self.json.accessors else { throw GLTFUnarchiveError.DataInconsistent("loadVertexAccessor: accessors is not defined") } let glAccessor = accessors[index] let vectorCount = glAccessor.count guard let usesFloatComponents = usesFloatComponentsMap[glAccessor.componentType] else { throw GLTFUnarchiveError.NotSupported("loadVertexAccessor: user defined accessor.componentType is not supported") } guard let componentsPerVector = componentsPerVectorMap[glAccessor.type] else { throw GLTFUnarchiveError.NotSupported("loadVertexAccessor: user defined accessor.type is not supported") } guard let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType] else { throw GLTFUnarchiveError.NotSupported("loadVertexAccessor: user defined accessor.componentType is not supported") } let dataOffset = glAccessor.byteOffset var bufferView: Data var dataStride: Int = bytesPerComponent * componentsPerVector var padding = 0 if let bufferViewIndex = glAccessor.bufferView { let bv = try self.loadBufferView(index: bufferViewIndex) bufferView = bv if let ds = try self.getDataStride(ofBufferViewIndex: bufferViewIndex) { guard ds >= dataStride else { throw GLTFUnarchiveError.DataInconsistent("loadVertexAccessor: dataStride is too small: \(ds) < \(dataStride)") } padding = ds - dataStride dataStride = ds } } else { let dataSize = dataStride * vectorCount bufferView = Data(count: dataSize) } /* print("==================================================") print("semantic: \(semantic)") print("vectorCount: \(vectorCount)") print("usesFloatComponents: \(usesFloatComponents)") print("componentsPerVector: \(componentsPerVector)") print("bytesPerComponent: \(bytesPerComponent)") print("dataOffset: \(dataOffset)") print("dataStride: \(dataStride)") print("bufferView.count: \(bufferView.count)") print("padding: \(padding)") print("dataOffset + dataStride * vectorCount - padding: \(dataOffset + dataStride * vectorCount - padding)") print("==================================================") */ #if SEEMS_TO_HAVE_VALIDATE_VERTEX_ATTRIBUTE_BUG // Metal validateVertexAttribute function seems to have a bug, so dateOffset must be 0. bufferView = bufferView.subdata(in: dataOffset..<dataOffset + dataStride * vectorCount - padding) let geometrySource = SCNGeometrySource(data: bufferView, semantic: semantic, vectorCount: vectorCount, usesFloatComponents: usesFloatComponents, componentsPerVector: componentsPerVector, bytesPerComponent: bytesPerComponent, dataOffset: 0, dataStride: dataStride) #else let geometrySource = SCNGeometrySource(data: bufferView, semantic: semantic, vectorCount: vectorCount, usesFloatComponents: usesFloatComponents, componentsPerVector: componentsPerVector, bytesPerComponent: bytesPerComponent, dataOffset: dataOffset, dataStride: dataStride) #endif self.accessors[index] = geometrySource glAccessor.didLoad(by: geometrySource, unarchiver: self) return geometrySource } private func createIndexAccessor(for source: SCNGeometrySource, primitiveMode: Int) throws -> SCNGeometryElement { assert(source.semantic == .vertex) guard let primitiveType = primitiveTypeMap[primitiveMode] else { throw GLTFUnarchiveError.NotSupported("createIndexAccessor: primitve mode \(primitiveMode) is not supported") } if source.vectorCount <= 0xFFFF { var indices = [UInt16](repeating: 0, count: source.vectorCount) for i in 0..<source.vectorCount { indices[i] = UInt16(i) } let geometryElement = SCNGeometryElement(indices: indices, primitiveType: primitiveType) return geometryElement } if source.vectorCount <= 0xFFFFFFFF { var indices = [UInt32](repeating: 0, count: source.vectorCount) for i in 0..<source.vectorCount { indices[i] = UInt32(i) } let geometryElement = SCNGeometryElement(indices: indices, primitiveType: primitiveType) return geometryElement } var indices = [UInt64](repeating: 0, count: source.vectorCount) for i in 0..<source.vectorCount { indices[i] = UInt64(i) } let geometryElement = SCNGeometryElement(indices: indices, primitiveType: primitiveType) return geometryElement } private func loadIndexAccessor(index: Int, primitiveMode: Int) throws -> SCNGeometryElement { guard index < self.accessors.count else { throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: out of index: \(index) < \(self.accessors.count)") } if let accessor = self.accessors[index] as? SCNGeometryElement { return accessor } //if (self.accessors[index] as? SCNGeometrySource) != nil { // throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: the accessor \(index) is defined as SCNGeometrySource") //} if self.accessors[index] != nil { throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: the accessor \(index) is not SCNGeometryElement") } guard let accessors = self.json.accessors else { throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: accessors is not defined") } let glAccessor = accessors[index] guard let primitiveType = primitiveTypeMap[primitiveMode] else { throw GLTFUnarchiveError.NotSupported("loadIndexAccessor: primitve mode \(primitiveMode) is not supported") } let primitiveCount = self.calcPrimitiveCount(ofCount: glAccessor.count, primitiveType: primitiveType) guard let usesFloatComponents = usesFloatComponentsMap[glAccessor.componentType] else { throw GLTFUnarchiveError.NotSupported("loadIndexAccessor: user defined accessor.componentType is not supported") } if usesFloatComponents { throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: cannot use Float for index accessor") } guard let componentsPerVector = componentsPerVectorMap[glAccessor.type] else { throw GLTFUnarchiveError.NotSupported("loadIndexAccessor: user defined accessor.type is not supported") } if componentsPerVector != 1 { throw GLTFUnarchiveError.DataInconsistent("loadIndexAccessor: accessor type must be SCALAR") } guard let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType] else { throw GLTFUnarchiveError.NotSupported("loadndexIAccessor: user defined accessor.componentType is not supported") } let dataOffset = glAccessor.byteOffset var bufferView: Data var dataStride: Int = bytesPerComponent if let bufferViewIndex = glAccessor.bufferView { let bv = try self.loadBufferView(index: bufferViewIndex) bufferView = bv if let ds = try self.getDataStride(ofBufferViewIndex: bufferViewIndex) { dataStride = ds } } else { let dataSize = dataStride * glAccessor.count bufferView = Data(count: dataSize) } let data = self.createIndexData(bufferView, offset: dataOffset, size: bytesPerComponent, stride: dataStride, count: glAccessor.count) let geometryElement = SCNGeometryElement(data: data, primitiveType: primitiveType, primitiveCount: primitiveCount, bytesPerIndex: bytesPerComponent) self.accessors[index] = geometryElement glAccessor.didLoad(by: geometryElement, unarchiver: self) return geometryElement } private func createNormalSource(for vertexSource: SCNGeometrySource, elements: [SCNGeometryElement]) throws -> SCNGeometrySource { let vertexArray = try createVertexArray(from: vertexSource) let dummyNormal = SCNVector3() var normals = [SCNVector3](repeating: dummyNormal, count: vertexArray.count) var counts = [Int](repeating: 0, count: vertexArray.count) for element in elements { if element.primitiveType != .triangles { throw GLTFUnarchiveError.NotSupported("createNormalSource: only triangles primitveType is supported: \(element.primitiveType)") } let indexArray = createIndexArray(from: element) var indexPos = 0 for _ in 0..<indexArray.count/3 { let i0 = indexArray[indexPos] let i1 = indexArray[indexPos+1] let i2 = indexArray[indexPos+2] let v0 = vertexArray[i0] let v1 = vertexArray[i1] let v2 = vertexArray[i2] let n = createNormal(v0, v1, v2) normals[i0] = add(normals[i0], n) normals[i1] = add(normals[i1], n) normals[i2] = add(normals[i2], n) counts[i0] += 1 counts[i1] += 1 counts[i2] += 1 indexPos += 3 } } for i in 0..<normals.count { if counts[i] != 0 { normals[i] = normalize(div(normals[i], SCNFloat(counts[i]))) } } let normalSource = SCNGeometrySource(normals: normals) return normalSource } private func loadKeyTimeAccessor(index: Int) throws -> ([NSNumber], CFTimeInterval) { guard index < self.accessors.count else { throw GLTFUnarchiveError.DataInconsistent("loadKeyTimeAccessor: out of index: \(index) < \(self.accessors.count)") } if let accessor = self.accessors[index] as? [NSNumber] { return (accessor, self.durations[index]!) } if self.accessors[index] != nil { throw GLTFUnarchiveError.DataInconsistent("loadKeyTimeAccessor: the accessor \(index) is not [Float]") } guard let accessors = self.json.accessors else { throw GLTFUnarchiveError.DataInconsistent("loadKeyTimeAccessor: accessors is not defined") } let glAccessor = accessors[index] guard let usesFloatComponents = usesFloatComponentsMap[glAccessor.componentType] else { throw GLTFUnarchiveError.NotSupported("loadKeyTimeAccessor: user defined accessor.componentType is not supported") } if !usesFloatComponents { throw GLTFUnarchiveError.DataInconsistent("loadKeyTimeAccessor: not Float keyTime accessor") } guard let componentsPerVector = componentsPerVectorMap[glAccessor.type] else { throw GLTFUnarchiveError.NotSupported("loadKeyTimeAccessor: user defined accessor.type is not supported") } if componentsPerVector != 1 { throw GLTFUnarchiveError.DataInconsistent("loadKeyTimeAccessor: accessor type must be SCALAR") } guard let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType] else { throw GLTFUnarchiveError.NotSupported("loadndexIAccessor: user defined accessor.componentType is not supported") } let dataOffset = glAccessor.byteOffset var bufferView: Data var dataStride: Int = bytesPerComponent if let bufferViewIndex = glAccessor.bufferView { let bv = try self.loadBufferView(index: bufferViewIndex) bufferView = bv if let ds = try self.getDataStride(ofBufferViewIndex: bufferViewIndex) { dataStride = ds } } else { let dataSize = dataStride * glAccessor.count bufferView = Data(count: dataSize) } let (keyTimeArray, duration) = createKeyTimeArray(from: bufferView, offset: dataOffset, stride: dataStride, count: glAccessor.count) self.accessors[index] = keyTimeArray self.durations[index] = duration return (keyTimeArray, duration) } private func loadValueAccessor(index: Int, flipW: Bool = false) throws -> [Any] { guard index < self.accessors.count else { throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: out of index: \(index) < \(self.accessors.count)") } if let accessor = self.accessors[index] as? [Any] { return accessor } if self.accessors[index] != nil { throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: the accessor \(index) is not [Float]") } guard let accessors = self.json.accessors else { throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: accessors is not defined") } let glAccessor = accessors[index] guard let bufferViewIndex = glAccessor.bufferView else { throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: bufferView is not defined") } /* guard let usesFloatComponents = usesFloatComponentsMap[glAccessor.componentType] else { throw GLTFUnarchiveError.NotSupported("loadValueAccessor: user defined accessor.componentType is not supported") } if usesFloatComponents { throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: not Float keyTime accessor") } guard let componentsPerVector = componentsPerVectorMap[glAccessor.type] else { throw GLTFUnarchiveError.NotSupported("loadValueAccessor: user defined accessor.type is not supported") } if componentsPerVector != 1 { throw GLTFUnarchiveError.DataInconsistent("loadValueAccessor: accessor type must be SCALAR") } guard let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType] else { throw GLTFUnarchiveError.NotSupported("loadValueAccessor: user defined accessor.componentType is not supported") } */ let dataOffset = glAccessor.byteOffset let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType]! let componentsPerVector = componentsPerVectorMap[glAccessor.type]! let dataStride = bytesPerComponent * componentsPerVector /* var bufferView: Data var dataStride: Int = bytesPerComponent if let bufferViewIndex = glAccessor.bufferView { let bv = try self.loadBufferView(index: bufferViewIndex) bufferView = bv if let ds = try self.getDataStride(ofBufferViewIndex: bufferViewIndex) { dataStride = ds } } else { let dataSize = dataStride * glAccessor.count bufferView = Data(count: dataSize) } */ //let valueArray = self.createValueArray(of: glAccessor) if glAccessor.type == "SCALAR" { var valueArray = [NSNumber]() valueArray.reserveCapacity(glAccessor.count) try self.iterateBufferView(index: bufferViewIndex, offset: dataOffset, stride: dataStride, count: glAccessor.count) { (p) in // TODO: it could be BYTE, UNSIGNED_BYTE, ... let value = p.load(fromByteOffset: 0, as: Float32.self) //let value = p.bindMemory(to: Float32.self, capacity: 1).pointee //print("value: \(value)") valueArray.append(NSNumber(value: value)) } self.accessors[index] = valueArray return valueArray } var valueArray = [NSValue]() valueArray.reserveCapacity(glAccessor.count) if glAccessor.type == "VEC3" { try self.iterateBufferView(index: bufferViewIndex, offset: dataOffset, stride: dataStride, count: glAccessor.count) { (p) in let x = p.load(fromByteOffset: 0, as: Float32.self) let y = p.load(fromByteOffset: 4, as: Float32.self) let z = p.load(fromByteOffset: 8, as: Float32.self) let v = SCNVector3(x, y, z) valueArray.append(NSValue(scnVector3: v)) } } else if glAccessor.type == "VEC4" { try self.iterateBufferView(index: bufferViewIndex, offset: dataOffset, stride: dataStride, count: glAccessor.count) { (p) in let x = p.load(fromByteOffset: 0, as: Float32.self) let y = p.load(fromByteOffset: 4, as: Float32.self) let z = p.load(fromByteOffset: 8, as: Float32.self) let w = p.load(fromByteOffset: 12, as: Float32.self) let v = SCNVector4(x, y, z, flipW ? -w : w) valueArray.append(NSValue(scnVector4: v)) } } return valueArray } private func loadImage(index: Int) throws -> Image { guard index < self.images.count else { throw GLTFUnarchiveError.DataInconsistent("loadImage: out of index: \(index) < \(self.images.count)") } if let image = self.images[index] { return image } guard let images = self.json.images else { throw GLTFUnarchiveError.DataInconsistent("loadImage: images is not defined") } let glImage = images[index] var image: Image? if let uri = glImage.uri { if let base64Str = self.getBase64Str(from: uri) { guard let data = Data(base64Encoded: base64Str) else { throw GLTFUnarchiveError.Unknown("loadImage: cannot convert the base64 string to Data") } image = try loadImageData(from: data) } else { let url = URL(fileURLWithPath: uri, relativeTo: self.directoryPath) image = try loadImageFile(from: url) } } else if let bufferViewIndex = glImage.bufferView { let bufferView = try self.loadBufferView(index: bufferViewIndex) image = try loadImageData(from: bufferView) } guard let _image = image else { throw GLTFUnarchiveError.Unknown("loadImage: image \(index) is not loaded") } self.images[index] = _image glImage.didLoad(by: _image, unarchiver: self) return _image } private func setSampler(index: Int, to property: SCNMaterialProperty) throws { guard let samplers = self.json.samplers else { throw GLTFUnarchiveError.DataInconsistent("setSampler: samplers is not defined") } if index >= samplers.count { throw GLTFUnarchiveError.DataInconsistent("setSampler: out of index: \(index) < \(samplers.count)") } let sampler = samplers[index] if let magFilter = sampler.magFilter { guard let filter = filterModeMap[magFilter] else { throw GLTFUnarchiveError.NotSupported("setSampler: magFilter \(magFilter) is not supported") } property.magnificationFilter = filter } if let minFilter = sampler.minFilter { switch minFilter { case GLTF_NEAREST: property.minificationFilter = .nearest property.mipFilter = .none case GLTF_LINEAR: property.minificationFilter = .linear property.mipFilter = .none case GLTF_NEAREST_MIPMAP_NEAREST: property.minificationFilter = .nearest property.mipFilter = .nearest case GLTF_LINEAR_MIPMAP_NEAREST: property.minificationFilter = .linear property.mipFilter = .nearest case GLTF_NEAREST_MIPMAP_LINEAR: property.minificationFilter = .nearest property.mipFilter = .linear case GLTF_LINEAR_MIPMAP_LINEAR: property.minificationFilter = .linear property.mipFilter = .linear default: throw GLTFUnarchiveError.NotSupported("setSampler: minFilter \(minFilter) is not supported") } } guard let wrapS = wrapModeMap[sampler.wrapS] else { throw GLTFUnarchiveError.NotSupported("setSampler: wrapS \(sampler.wrapS) is not supported") } property.wrapS = wrapS guard let wrapT = wrapModeMap[sampler.wrapT] else { throw GLTFUnarchiveError.NotSupported("setSampler: wrapT \(sampler.wrapT) is not supported") } property.wrapT = wrapT } private func loadTexture(index: Int) throws -> SCNMaterialProperty { guard index < self.textures.count else { throw GLTFUnarchiveError.DataInconsistent("loadTexture: out of index: \(index) < \(self.textures.count)") } if let texture = self.textures[index] { return texture } guard let textures = self.json.textures else { throw GLTFUnarchiveError.DataInconsistent("loadTexture: textures is not defined") } let glTexture = textures[index] guard let sourceIndex = glTexture.source else { throw GLTFUnarchiveError.NotSupported("loadTexture: texture without source is not supported") } let image = try self.loadImage(index: sourceIndex) let texture = SCNMaterialProperty(contents: image) // enable Texture filtering sample so we get less aliasing when they are farther away texture.mipFilter = .linear // TODO: retain glTexture.name somewhere if let sampler = glTexture.sampler { try self.setSampler(index: sampler, to: texture) } else { // set default values texture.wrapS = .repeat texture.wrapT = .repeat } self.textures[index] = texture glTexture.didLoad(by: texture, unarchiver: self) return texture } func setTexture(index: Int, to property: SCNMaterialProperty) throws { let texture = try self.loadTexture(index: index) guard let contents = texture.contents else { throw GLTFUnarchiveError.DataInconsistent("setTexture: contents of texture \(index) is nil") } property.contents = contents property.minificationFilter = texture.minificationFilter property.magnificationFilter = texture.magnificationFilter property.mipFilter = texture.mipFilter property.wrapS = texture.wrapS property.wrapT = texture.wrapT property.intensity = texture.intensity property.maxAnisotropy = texture.maxAnisotropy property.contentsTransform = texture.contentsTransform property.mappingChannel = texture.mappingChannel if #available(OSX 10.13, *) { property.textureComponents = texture.textureComponents } } var defaultMaterial: SCNMaterial { get { let material = SCNMaterial() material.lightingModel = .physicallyBased material.diffuse.contents = createColor([1.0, 1.0, 1.0, 1.0]) material.metalness.contents = createGrayColor(white: 1.0) material.roughness.contents = createGrayColor(white: 1.0) material.isDoubleSided = false return material } } private func loadMaterial(index: Int) throws -> SCNMaterial { guard index < self.materials.count else { throw GLTFUnarchiveError.DataInconsistent("loadMaterial: out of index: \(index) < \(self.materials.count)") } if let material = self.materials[index] { return material } guard let materials = self.json.materials else { throw GLTFUnarchiveError.DataInconsistent("loadMaterials: materials it not defined") } let glMaterial = materials[index] let material = SCNMaterial() self.materials[index] = material material.name = glMaterial.name material.setValue(Float(1.0), forKey: "baseColorFactorR") material.setValue(Float(1.0), forKey: "baseColorFactorG") material.setValue(Float(1.0), forKey: "baseColorFactorB") material.setValue(Float(1.0), forKey: "baseColorFactorA") material.setValue(Float(1.0), forKey: "metallicFactor") material.setValue(Float(1.0), forKey: "roughnessFactor") material.setValue(glMaterial.emissiveFactor[0], forKey: "emissiveFactorR") material.setValue(glMaterial.emissiveFactor[1], forKey: "emissiveFactorG") material.setValue(glMaterial.emissiveFactor[2], forKey: "emissiveFactorB") material.setValue(glMaterial.alphaCutoff, forKey: "alphaCutoff") if let pbr = glMaterial.pbrMetallicRoughness { material.lightingModel = .physicallyBased material.diffuse.contents = createColor(pbr.baseColorFactor) material.metalness.contents = createGrayColor(white: pbr.metallicFactor) material.roughness.contents = createGrayColor(white: pbr.roughnessFactor) if let baseTexture = pbr.baseColorTexture { try self.setTexture(index: baseTexture.index, to: material.diffuse) material.diffuse.mappingChannel = baseTexture.texCoord //let baseColorFactor = createVector4(pbr.baseColorFactor) //material.setValue(NSValue(scnVector4: baseColorFactor), forKeyPath: "baseColorFactor") material.setValue(pbr.baseColorFactor[0], forKey: "baseColorFactorR") material.setValue(pbr.baseColorFactor[1], forKey: "baseColorFactorG") material.setValue(pbr.baseColorFactor[2], forKey: "baseColorFactorB") material.setValue(pbr.baseColorFactor[3], forKey: "baseColorFactorA") } if let metallicTexture = pbr.metallicRoughnessTexture { try self.setTexture(index: metallicTexture.index, to: material.metalness) material.metalness.mappingChannel = metallicTexture.texCoord try self.setTexture(index: metallicTexture.index, to: material.roughness) material.roughness.mappingChannel = metallicTexture.texCoord if #available(OSX 10.13, *) { material.metalness.textureComponents = .blue material.roughness.textureComponents = .green } else { // Fallback on earlier versions if let image = material.metalness.contents as? Image { let (metalness, roughness) = try getMetallicRoughnessTexture(from: image) material.metalness.contents = metalness material.roughness.contents = roughness } } let metallicFactor = pbr.metallicFactor material.setValue(metallicFactor, forKey: "metallicFactor") let roughnessFactor = pbr.roughnessFactor material.setValue(roughnessFactor, forKey: "roughnessFactor") } } if let normalTexture = glMaterial.normalTexture { try self.setTexture(index: normalTexture.index, to: material.normal) material.normal.mappingChannel = normalTexture.texCoord // TODO: - use normalTexture.scale } if let occlusionTexture = glMaterial.occlusionTexture { try self.setTexture(index: occlusionTexture.index, to: material.ambientOcclusion) material.ambientOcclusion.mappingChannel = occlusionTexture.texCoord material.ambientOcclusion.intensity = CGFloat(occlusionTexture.strength) } if let emissiveTexture = glMaterial.emissiveTexture { if material.lightingModel == .physicallyBased { material.selfIllumination.contents = nil } try self.setTexture(index: emissiveTexture.index, to: material.emission) material.emission.mappingChannel = emissiveTexture.texCoord } material.isDoubleSided = glMaterial.doubleSided material.shaderModifiers = [ .surface: try! String(contentsOf: URL(fileURLWithPath: bundle.path(forResource: "GLTFShaderModifierSurface", ofType: "shader")!), encoding: String.Encoding.utf8) ] #if SEEMS_TO_HAVE_DOUBLESIDED_BUG if material.isDoubleSided { material.shaderModifiers = [ .surface: try! String(contentsOf: URL(fileURLWithPath: bundle.path(forResource: "GLTFShaderModifierSurface_doubleSidedWorkaround", ofType: "shader")!), encoding: String.Encoding.utf8) ] } #endif switch glMaterial.alphaMode { case "OPAQUE": material.blendMode = .replace case "BLEND": material.blendMode = .alpha material.writesToDepthBuffer = false material.shaderModifiers![.surface] = try! String(contentsOf: URL(fileURLWithPath: bundle.path(forResource: "GLTFShaderModifierSurface_alphaModeBlend", ofType: "shader")!), encoding: String.Encoding.utf8) case "MASK": material.shaderModifiers![.fragment] = try! String(contentsOf: URL(fileURLWithPath: bundle.path(forResource: "GLTFShaderModifierFragment_alphaCutoff", ofType: "shader")!), encoding: String.Encoding.utf8) default: throw GLTFUnarchiveError.NotSupported("loadMaterial: alphaMode \(glMaterial.alphaMode) is not supported") } glMaterial.didLoad(by: material, unarchiver: self) return material } private func loadAttributes(_ attributes: [String: GLTFGlTFid]) throws -> [SCNGeometrySource] { var sources = [SCNGeometrySource]() // Sort attributes to keep correct semantic order for (attribute, accessorIndex) in attributes.sorted(by: { $0.0 < $1.0 }) { if let semantic = attributeMap[attribute] { let accessor = try self.loadVertexAccessor(index: accessorIndex, semantic: semantic) sources.append(accessor) } else { // user defined semantic throw GLTFUnarchiveError.NotSupported("loadMesh: user defined semantic is not supported: " + attribute) } } return sources } private func loadMesh(index: Int) throws -> SCNNode { guard index < self.meshes.count else { throw GLTFUnarchiveError.DataInconsistent("loadMesh: out of index: \(index) < \(self.meshes.count)") } if let mesh = self.meshes[index] { return mesh.clone() } guard let meshes = self.json.meshes else { throw GLTFUnarchiveError.DataInconsistent("loadMesh: meshes it not defined") } let glMesh = meshes[index] let node = SCNNode() self.meshes[index] = node if let name = glMesh.name { node.name = name } var weightPaths = [String]() for i in 0..<glMesh.primitives.count { let primitive = glMesh.primitives[i] let primitiveNode = SCNNode() //var sources = [SCNGeometrySource]() //var vertexSource: SCNGeometrySource? //var normalSource: SCNGeometrySource? /* for (attribute, accessorIndex) in primitive.attributes { if let semantic = attributeMap[attribute] { let accessor = try self.loadVertexAccessor(index: accessorIndex, semantic: semantic) sources.append(accessor) if semantic == .vertex { vertexSource = accessor } else if semantic == .normal { normalSource = accessor } } else { // user defined semantic throw GLTFUnarchiveError.NotSupported("loadMesh: user defined semantic is not supported: " + attribute) } } */ var sources = try self.loadAttributes(primitive.attributes) let vertexSource = sources.first { $0.semantic == .vertex } var normalSource = sources.first { $0.semantic == .normal } var elements = [SCNGeometryElement]() if let indexIndex = primitive.indices { let accessor = try self.loadIndexAccessor(index: indexIndex, primitiveMode: primitive.mode) elements.append(accessor) } else if let vertexSource = vertexSource { let accessor = try self.createIndexAccessor(for: vertexSource, primitiveMode: primitive.mode) elements.append(accessor) } else { // Should it be error? } if normalSource == nil { if let vertexSource = vertexSource { normalSource = try self.createNormalSource(for: vertexSource, elements: elements) sources.append(normalSource!) } else { // Should it be error? } } let geometry = SCNGeometry(sources: sources, elements: elements) primitiveNode.geometry = geometry if let materialIndex = primitive.material { let material = try self.loadMaterial(index: materialIndex) geometry.materials = [material] } else { let material = self.defaultMaterial geometry.materials = [material] } if let targets = primitive.targets { let morpher = SCNMorpher() for targetIndex in 0..<targets.count { let target = targets[targetIndex] let sources = try self.loadAttributes(target) let geometry = SCNGeometry(sources: sources, elements: nil) if let extras = glMesh.extras, let extrasTargetNames = extras.extensions["TargetNames"] as? GLTFExtrasTargetNames, let targetNames = extrasTargetNames.targetNames { geometry.name = targetNames[targetIndex] } else if let accessor = self.json.accessors?[target["POSITION"]!], let name = accessor.name { geometry.name = name } morpher.targets.append(geometry) let weightPath = "childNodes[0].childNodes[\(i)].morpher.weights[\(targetIndex)]" weightPaths.append(weightPath) } morpher.calculationMode = .additive primitiveNode.morpher = morpher } node.addChildNode(primitiveNode) } // TODO: set default weights /* if let weights = glMesh.weights { for i in 0..<weights.count { print("keyPath: \(weightPaths[i])") node.setValue(0.123, forKeyPath: weightPaths[i]) print("value: \(node.value(forKeyPath: weightPaths[i]))") //print("v: \(node.childNodes[0].childNodes[0].morpher?.wefight(forTargetAt: i))") node.setValue(weights[i], forKeyPath: weightPaths[i]) } //node.setValue(0.234, forKeyPath: "childNodes[0].morpher.weights[") //print("value: \(node.childNodes[0].morpher?.weight(forTargetAt: 0))") } */ //node.childNodes[0].morpher?.setWeight(1.0, forTargetAt: 0) //node.childNodes[0].morpher?.setWeight(1.0, forTargetAt: 1) glMesh.didLoad(by: node, unarchiver: self) return node } private func loadAnimationSampler(index: Int, sampler: Int, flipW: Bool = false) throws -> CAAnimationGroup { guard index < self.animationSamplers.count else { throw GLTFUnarchiveError.DataInconsistent("loadAnimationSampler: out of index: \(index) < \(self.animationSamplers.count)") } if let animationSamplers = self.animationSamplers[index] { if animationSamplers.count > sampler, let animation = animationSamplers[sampler] { //return animation.copy() as! CAKeyframeAnimation return animation.copy() as! CAAnimationGroup } } else { self.animationSamplers[index] = [CAAnimation?]() } if self.animationSamplers[index]!.count <= sampler { for _ in self.animationSamplers[index]!.count...sampler { self.animationSamplers[index]!.append(nil) } } guard let animations = self.json.animations else { throw GLTFUnarchiveError.DataInconsistent("loadAnimationSampler: animations is not defined") } let glAnimation = animations[index] guard sampler < glAnimation.samplers.count else { throw GLTFUnarchiveError.DataInconsistent("loadAnimationSampler: out of index: sampler \(sampler) < \(glAnimation.samplers.count)") } let glSampler = glAnimation.samplers[sampler] let animation = CAKeyframeAnimation() // LINEAR, STEP, CATMULLROMSPLINE, CUBICSPLINE let (keyTimes, duration) = try self.loadKeyTimeAccessor(index: glSampler.input) //let timingFunctions = let values = try self.loadValueAccessor(index: glSampler.output, flipW: flipW) animation.keyTimes = keyTimes animation.values = values animation.repeatCount = .infinity animation.duration = duration //animation.timingFunctions = timingFunctions let group = CAAnimationGroup() group.animations = [animation] group.duration = self.maxAnimationDuration group.repeatCount = .infinity self.animationSamplers[index]![sampler] = group return group } private func loadWeightAnimationsSampler(index: Int, sampler: Int, paths: [String]) throws -> CAAnimationGroup { guard index < self.animationSamplers.count else { throw GLTFUnarchiveError.DataInconsistent("loadWeightAnimationsSampler: out of index: \(index) < \(self.animationSamplers.count)") } if let animationSamplers = self.animationSamplers[index] { if let animation = animationSamplers[sampler] { return animation.copy() as! CAAnimationGroup } } guard let glAnimations = self.json.animations else { throw GLTFUnarchiveError.DataInconsistent("loadWeightAnimationsSampler: animations is not defined") } let glAnimation = glAnimations[index] guard sampler < glAnimation.samplers.count else { throw GLTFUnarchiveError.DataInconsistent("loadWeightAnimationsSampler: out of index: sampler \(sampler) < \(glAnimation.samplers.count)") } let glSampler = glAnimation.samplers[sampler] let (keyTimes, duration) = try self.loadKeyTimeAccessor(index: glSampler.input) guard let values = try self.loadValueAccessor(index: glSampler.output) as? [NSNumber] else { throw GLTFUnarchiveError.DataInconsistent("loadWeightAnimationsSampler: data type is not [NSNumber]") } let group = CAAnimationGroup() group.duration = duration //group.animations = [] var animations = [CAKeyframeAnimation]() for path in paths { let animation = CAKeyframeAnimation() animation.keyPath = path animation.keyTimes = keyTimes //animation.values = [NSNumber]() //animation.repeatCount = .infinity animation.duration = duration animations.append(animation) } group.animations = animations group.repeatCount = .infinity let step = animations.count let dataLength = values.count / step guard dataLength == keyTimes.count else { throw GLTFUnarchiveError.DataInconsistent("loadWeightAnimationsSampler: data count mismatch: \(dataLength) != \(keyTimes.count)") } for i in 0..<animations.count { var valueIndex = i var v = [NSNumber]() v.reserveCapacity(dataLength) for _ in 0..<dataLength { v.append(values[valueIndex]) valueIndex += step } animations[i].values = v } return group } //private func loadAnimation(index: Int, channel: Int) throws -> SCNAnimation { private func loadAnimation(index: Int, channel: Int, weightPaths: [String]?) throws -> CAAnimation { guard index < self.animationChannels.count else { throw GLTFUnarchiveError.DataInconsistent("loadAnimation: out of index: \(index) < \(self.animationChannels.count)") } if let animationChannels = self.animationChannels[index] { if let animation = animationChannels[channel] { return animation } } guard let animations = self.json.animations else { throw GLTFUnarchiveError.DataInconsistent("loadAnimation: animations is not defined") } let glAnimation = animations[index] guard channel < glAnimation.channels.count else { throw GLTFUnarchiveError.DataInconsistent("loadAnimation: out of index: channel \(channel) < \(glAnimation.channels.count)") } let glChannel = glAnimation.channels[channel] // Animation Channel Target guard let nodeIndex = glChannel.target.node else { throw GLTFUnarchiveError.NotSupported("loadAnimation: animation without node target is not supported") } let node = try self.loadNode(index: nodeIndex) let keyPath = glAnimation.channels[channel].target.path //let animation = CAKeyframeAnimation(keyPath: keyPath) // Animation Sampler let samplerIndex = glChannel.sampler /* guard samplerIndex < glAnimation.samplers.count else { throw GLTFUnarchiveError.DataInconsistent("loadAnimation: out of index: sampler \(samplerIndex) < \(glAnimation.samplers.count)") } let glSampler = glAnimation.samplers[samplerIndex] */ var animation: CAAnimation if keyPath == "weights" { guard let weightPaths = weightPaths else { throw GLTFUnarchiveError.DataInconsistent("loadAnimation: morpher is not defined)") } animation = try self.loadWeightAnimationsSampler(index: index, sampler: samplerIndex, paths: weightPaths) } else { let flipW = false //let flipW = keyPath == "rotation" //let keyframeAnimation = try self.loadAnimationSampler(index: index, sampler: samplerIndex) let group = try self.loadAnimationSampler(index: index, sampler: samplerIndex, flipW: flipW) let keyframeAnimation = group.animations![0] as! CAKeyframeAnimation guard let animationKeyPath = keyPathMap[keyPath] else { throw GLTFUnarchiveError.NotSupported("loadAnimation: animation key \(keyPath) is not supported") } keyframeAnimation.keyPath = animationKeyPath animation = group } //let scnAnimation = SCNAnimation(caAnimation: animation) //node.addAnimation(scnAnimation, forKey: keyPath) node.addAnimation(animation, forKey: keyPath) //glAnimation.didLoad(by: scnAnimation, unarchiver: self) glAnimation.didLoad(by: animation, unarchiver: self) //return scnAnimation return animation } //@available(OSX 10.13, *) private func loadAnimation(forNode index: Int) throws { guard let animations = self.json.animations else { return } let node = try self.loadNode(index: index) let weightPaths = node.value(forUndefinedKey: "weightPaths") as? [String] for i in 0..<animations.count { let animation = animations[i] for j in 0..<animation.channels.count { let channel = animation.channels[j] if channel.target.node == index { let animation = try self.loadAnimation(index: i, channel: j, weightPaths: weightPaths) node.addAnimation(animation, forKey: nil) } } } } private func getMaxAnimationDuration() throws -> CFTimeInterval { guard let animations = self.json.animations else { return 0.0 } guard let accessors = self.json.accessors else { return 0.0 } var duration: CFTimeInterval = 0.0 for animation in animations { for sampler in animation.samplers { let accessor = accessors[sampler.input] if let max = accessor.max { guard max.count == 1 else { throw GLTFUnarchiveError.DataInconsistent("getMaxAnimationDuration: keyTime must be SCALAR type") } if CFTimeInterval(max[0]) > duration { duration = CFTimeInterval(max[0]) } } } } return duration } private func loadInverseBindMatrices(index: Int) throws -> [NSValue] { guard index < self.accessors.count else { throw GLTFUnarchiveError.DataInconsistent("loadInverseBindMatrices: out of index: \(index) < \(self.accessors.count)") } if let accessor = self.accessors[index] as? [NSValue] { return accessor } if self.accessors[index] != nil { throw GLTFUnarchiveError.DataInconsistent("loadInverseBindMatrices: the accessor \(index) is not [SCNMatrix4]") } guard let accessors = self.json.accessors else { throw GLTFUnarchiveError.DataInconsistent("loadInverseBindMatrices: accessors is not defined") } let glAccessor = accessors[index] let vectorCount = glAccessor.count guard usesFloatComponentsMap[glAccessor.componentType] != nil else { throw GLTFUnarchiveError.NotSupported("loadInverseBindMatrices: user defined accessor.componentType is not supported") } guard glAccessor.type == "MAT4" else { throw GLTFUnarchiveError.DataInconsistent("loadInverseBindMatrices: type must be MAT4: \(glAccessor.type)") } guard let componentsPerVector = componentsPerVectorMap[glAccessor.type] else { throw GLTFUnarchiveError.NotSupported("loadInverseBindMatrices: user defined accessor.type is not supported") } guard let bytesPerComponent = bytesPerComponentMap[glAccessor.componentType] else { throw GLTFUnarchiveError.NotSupported("loadInverseBindMatrices: user defined accessor.componentType is not supported") } let dataOffset = glAccessor.byteOffset //var bufferView: Data let dataStride: Int = bytesPerComponent * componentsPerVector //var padding = 0 var matrices = [NSValue]() guard let bufferViewIndex = glAccessor.bufferView else { for _ in 0..<vectorCount { matrices.append(NSValue(scnMatrix4: SCNMatrix4Identity)) } self.accessors[index] = matrices glAccessor.didLoad(by: matrices, unarchiver: self) return matrices } try self.iterateBufferView(index: bufferViewIndex, offset: dataOffset, stride: dataStride, count: glAccessor.count) { (p) in // TODO: it could be BYTE, UNSIGNED_BYTE, ... var values = [Float]() for i in 0..<16 { let value = p.load(fromByteOffset: i*4, as: Float.self) values.append(value) } let v: [SCNFloat] = values.map { SCNFloat($0) } let matrix = SCNMatrix4( m11: v[0], m12: v[1], m13: v[2], m14: v[3], m21: v[4], m22: v[5], m23: v[6], m24: v[7], m31: v[8], m32: v[9], m33: v[10], m34: v[11], m41: v[12], m42: v[13], m43: v[14], m44: v[15]) matrices.append(NSValue(scnMatrix4: matrix)) } self.accessors[index] = matrices glAccessor.didLoad(by: matrices, unarchiver: self) return matrices } private func loadSkin(index: Int, meshNode: SCNNode) throws -> SCNSkinner { guard index < self.skins.count else { throw GLTFUnarchiveError.DataInconsistent("loadSkin: out of index: \(index) < \(self.skins.count)") } if let skin = self.skins[index] { return skin } guard let skins = self.json.skins else { throw GLTFUnarchiveError.DataInconsistent("loadSkin: 'skins' is not defined") } let glSkin = skins[index] var joints = [SCNNode]() for joint in glSkin.joints { let node = try self.loadNode(index: joint) joints.append(node) } var boneInverseBindTransforms: [NSValue]? if let inverseBindMatrices = glSkin.inverseBindMatrices { boneInverseBindTransforms = try self.loadInverseBindMatrices(index: inverseBindMatrices) } //var baseNode: SCNNode? if let skeleton = glSkin.skeleton { _ = try self.loadNode(index: skeleton) } //var boneWeights: SCNGeometrySource? //var boneIndices: SCNGeometrySource? //var baseGeometry: SCNGeometry? //var skeleton: SCNNode? var _skinner: SCNSkinner? for primitive in meshNode.childNodes { if let weights = primitive.geometry?.sources(for: .boneWeights) { let boneWeights = weights[0] let baseGeometry = primitive.geometry! guard let _joints = primitive.geometry?.sources(for: .boneIndices) else { throw GLTFUnarchiveError.DataInconsistent("loadSkin: JOINTS_0 is not defined") } let boneIndices = _joints[0] #if SEEMS_TO_HAVE_SKINNER_VECTOR_TYPE_BUG // This code doesn't solve the problem. #if false if _joints[0].dataStride == 8 { let device = MTLCreateSystemDefaultDevice()! let numComponents = _joints[0].vectorCount * _joints[0].componentsPerVector _joints[0].data.withUnsafeBytes { (ptr: UnsafePointer<UInt16>) in let buffer = device.makeBuffer(bytes: ptr, length: 2 * numComponents, options: [])! let source = SCNGeometrySource(buffer: buffer, vertexFormat: .ushort4, semantic: .boneIndices, vertexCount: _joints[0].vectorCount, dataOffset: 0, dataStride: _joints[0].dataStride) boneIndices = source } } #endif #endif let skinner = SCNSkinner(baseGeometry: baseGeometry, bones: joints, boneInverseBindTransforms: boneInverseBindTransforms, boneWeights: boneWeights, boneIndices: boneIndices) skinner.skeleton = primitive primitive.skinner = skinner _skinner = skinner } } /* guard let _boneWeights = boneWeights else { throw GLTFUnarchiveError.DataInconsistent("loadSkin: WEIGHTS_0 is not defined") } guard let _boneIndices = boneIndices else { throw GLTFUnarchiveError.DataInconsistent("loadSkin: JOINTS_0 is not defined") } let skinner = SCNSkinner(baseGeometry: baseGeometry, bones: joints, boneInverseBindTransforms: boneInverseBindTransforms, boneWeights: _boneWeights, boneIndices: _boneIndices) skinner.skeleton = skeleton skeleton?.skinner = skinner self.skins[index] = skinner */ guard let skinner = _skinner else { throw GLTFUnarchiveError.DataInconsistent("loadSkin: skinner is not defined") } glSkin.didLoad(by: skinner, unarchiver: self) return skinner } private func loadNode(index: Int) throws -> SCNNode { guard index < self.nodes.count else { throw GLTFUnarchiveError.DataInconsistent("loadNode: out of index: \(index) < \(self.nodes.count)") } if let node = self.nodes[index] { return node } guard let nodes = self.json.nodes else { throw GLTFUnarchiveError.DataInconsistent("loadNode: nodes is not defined") } let glNode = nodes[index] let scnNode = SCNNode() self.nodes[index] = scnNode if let name = glNode.name { scnNode.name = name } if let camera = glNode.camera { scnNode.camera = try self.loadCamera(index: camera) } if let mesh = glNode.mesh { let meshNode = try self.loadMesh(index: mesh) scnNode.addChildNode(meshNode) var weightPaths = [String]() for i in 0..<meshNode.childNodes.count { let primitive = meshNode.childNodes[i] if let morpher = primitive.morpher { for j in 0..<morpher.targets.count { let path = "childNodes[0].childNodes[\(i)].morpher.weights[\(j)]" weightPaths.append(path) } } } scnNode.setValue(weightPaths, forUndefinedKey: "weightPaths") if let skin = glNode.skin { _ = try self.loadSkin(index: skin, meshNode: meshNode) //scnNode.skinner = skinner } } if let matrix = glNode._matrix { scnNode.transform = createMatrix4(matrix) if glNode._rotation != nil || glNode._scale != nil || glNode._translation != nil { throw GLTFUnarchiveError.DataInconsistent("loadNode: both matrix and rotation/scale/translation are defined") } } else { //scnNode.orientation = createVector4ForOrientation(glNode.rotation) scnNode.orientation = createVector4(glNode.rotation) scnNode.scale = createVector3(glNode.scale) scnNode.position = createVector3(glNode.translation) } if glNode.weights != nil { // load weights } if let children = glNode.children { for child in children { let scnChild = try self.loadNode(index: child) scnNode.addChildNode(scnChild) } } try self.loadAnimation(forNode: index) glNode.didLoad(by: scnNode, unarchiver: self) return scnNode } func loadScene() throws -> SCNScene { if let sceneIndex = self.json.scene { return try self.loadScene(index: sceneIndex) } return try self.loadScene(index: 0) } private func loadScene(index: Int) throws -> SCNScene { guard index < self.scenes.count else { throw GLTFUnarchiveError.DataInconsistent("loadScene: out of index: \(index) < \(self.scenes.count)") } if let scene = self.scenes[index] { return scene } guard let scenes = self.json.scenes else { throw GLTFUnarchiveError.DataInconsistent("loadScene: scenes is not defined") } let glScene = scenes[index] let scnScene = SCNScene() self.maxAnimationDuration = try self.getMaxAnimationDuration() if let name = glScene.name { scnScene.setValue(name, forKey: "name") } if let nodes = glScene.nodes { for node in nodes { let scnNode = try self.loadNode(index: node) scnScene.rootNode.addChildNode(scnNode) } } self.scenes[index] = scnScene glScene.didLoad(by: scnScene, unarchiver: self) self.json.didLoad(by: scnScene, unarchiver: self) return scnScene } func loadScenes() throws { guard let scenes = self.json.scenes else { return } for index in 0..<scenes.count { _ = try self.loadScene(index: index) } } }
mit
3b6ab4c31ccb436a9969062fe5e42cc1
42.146356
280
0.595411
5.326519
false
false
false
false
tuanphung/ATSwiftKit
Source/Extensions/UIKit/UIActionSheet+ATS.swift
1
3480
// // UIActionSheet+AT.swift // // Copyright (c) 2015 PHUNG ANH TUAN. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit var UIActionSheetClosureKey = "UIActionSheetClosureKey" public typealias UIActionSheetClosure = (selectedOption: String) -> () public extension UIActionSheet { private var handler: UIActionSheetClosure? { set(value) { let closure = ATSClosureWrapper(closure: value) objc_setAssociatedObject(self, &UIActionSheetClosureKey, closure, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN)) } get { if let wrapper = objc_getAssociatedObject(self, &UIActionSheetClosureKey) as? ATSClosureWrapper<UIActionSheetClosure>{ return wrapper.closure } return nil } } class func showInView(view: UIView?, title: String?, cancelButtonTitle: String?, otherButtonTitles: [String]?, handler: UIActionSheetClosure?) -> UIActionSheet { return self.showInView(view, title: title, cancelButtonTitle: cancelButtonTitle, destructiveButtonTitle: nil, otherButtonTitles: otherButtonTitles, handler: handler) } class func showInView(view: UIView?, title: String?, cancelButtonTitle: String?, destructiveButtonTitle: String?, otherButtonTitles: [String]?, handler: UIActionSheetClosure?) -> UIActionSheet { var actionSheet = UIActionSheet(title: title, delegate: nil, cancelButtonTitle: cancelButtonTitle, destructiveButtonTitle: destructiveButtonTitle) actionSheet.delegate = actionSheet if let _otherButtonTitles = otherButtonTitles { for buttonTitle in _otherButtonTitles { actionSheet.addButtonWithTitle(buttonTitle) } } if let _cancelButtonTitle = cancelButtonTitle { actionSheet.cancelButtonIndex = actionSheet.addButtonWithTitle(cancelButtonTitle!) } actionSheet.handler = handler dispatch_async(dispatch_get_main_queue(), { if let _view = view { actionSheet.showInView(_view) } }) return actionSheet } } extension UIActionSheet: UIActionSheetDelegate { public func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { actionSheet.handler?(selectedOption: actionSheet.buttonTitleAtIndex(buttonIndex)) } }
mit
fdc0e4c70ae8ea36b60dbdb123ded83a
43.628205
198
0.706034
5.420561
false
false
false
false
Rendel27/RDExtensionsSwift
RDExtensionsSwift/RDExtensionsSwift/Source/UIImage/UIImage+Init.swift
1
5919
// // UIImage+Init.swift // // Created by Giorgi Iashvili on 19.09.16. // Copyright (c) 2016 Giorgi Iashvili // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import ImageIO public extension UIImage { /// RDExtensionsSwift: Return newly initialized image from given color with given size convenience init(color: UIColor, size: CGSize) { UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.init(cgImage: (img?.cgImage!)!) } /// RDExtensionsSwift: Return unique identifier and download image from the given url static func download(_ url: URL, completeInMainThread: Bool = true, completion: ((_ image: UIImage?, _ id: String) -> Void)?) -> String { return Data.download(url, completion: { (data, id) in var img : UIImage? if let d = data { img = UIImage(data: d) } if(completeInMainThread) { DispatchQueue.main.async(execute: { completion?(img, id) }) } else { completion?(img, id) } }) } /// RDExtensionsSwift: Return newly initialized animated image by given name static func gif(_ named: String) -> UIImage? { var image : UIImage? if let n = named.components(separatedBy: ".gif").first, let url = Bundle.main.url(forResource: n, withExtension: ".gif") { image = self.gif(url) } return image } /// RDExtensionsSwift: Return newly initialized animated image by given url static func gif(_ url: URL) -> UIImage? { var image : UIImage? if let s = CGImageSourceCreateWithURL(url as CFURL, nil) { image = self.gif(s) } return image } /// RDExtensionsSwift: Return newly animated image by given data static func gif(_ data: Data) -> UIImage? { var image : UIImage? if let d = CGImageSourceCreateWithData(data as CFData, nil) { image = self.gif(d) } return image } /// RDExtensionsSwift: Return newly initialized image by given source static func gif(_ source: CGImageSource) -> UIImage? { let count = CGImageSourceGetCount(source) var images : [CGImage] = [] var delay : [Int] = [] for i in stride(from: 0, to: count, by: 1) { images.append(CGImageSourceCreateImageAtIndex(source, i, nil)!) var d = 1 if let p = CGImageSourceCopyPropertiesAtIndex(source, i, nil) { if let gp = (p as Dictionary)[kCGImagePropertyGIFDictionary] { if var n = gp[kCGImagePropertyGIFUnclampedDelayTime as String] as? CGFloat { if(n == 0) { n = gp[kCGImagePropertyGIFDelayTime as String] as! CGFloat } else if(n > 0) { d = Int(n * 100) } } } } delay.append(d) } var td = 0 for i in delay { td += i } var frames : [UIImage] = [] if(count == images.count && images.count == delay.count && count == delay.count) { var hcf = delay.first ?? 0 for i in stride(from: 1, to: count, by: 1) { var n1 = delay[i] var n2 = hcf if(n1 > n2) { n1 = hcf n2 = delay[i] } while(true) { let x = n1 % n2 if(x == 0) { hcf = n2 break } n1 = n2 n2 = x } } for i in stride(from: 0, to: count, by: 1) { let frame = UIImage(cgImage: images[i]) for _ in stride(from: 0, through: delay[i] / hcf, by: 1).reversed() { frames.append(frame) } } } else { print("GIF ERROR: Cannot extract gif frames") } return UIImage.animatedImage(with: frames, duration: TimeInterval(td)/100) } }
mit
3759791cc25b6c768ddc2df5f14a2a6b
33.213873
139
0.521372
4.863599
false
false
false
false
RobinChao/JSON-Parse-Code
MagicJSON/Source/Operators.swift
1
1049
// // Operators.swift // MagicJSON // // Created by Robin on 4/9/16. // Copyright © 2016 Robin. All rights reserved. // import Foundation infix operator <*> { associativity left precedence 100 } //左结合的left,优先级100 func <*><A, B>(f: (A -> B?)?, x: A?) -> B? { guard let f = f, x = x else { return .None } return f(x) } infix operator <~~ { associativity left precedence 110 } //左结合的left,优先级110 func <~~<A, B>(x: A?, f: (A -> B?)) -> B? { guard let x = x else { return .None } return f(x) } infix operator <<~ { associativity left precedence 110 } //左结合的left,优先级110 func <<~<A, B>(x: [A]?, f: (A -> B?)) -> [B]? { guard let x = x else { return nil } return x.map(f).flatMap{ $0 } } infix operator <?> { associativity left precedence 100 } //左结合的left,优先级100 func <?><A, B>(f: (A? -> B)?, x: A?) -> B? { guard let f = f else { return nil } return f(x) }
mit
ca814d49afaa305fc1bd9f841b16af50
13.686567
48
0.517276
2.963855
false
false
false
false