repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
DerrickQin2853/SinaWeibo-Swift
SinaWeibo/SinaWeibo/Classes/View/EmoticonKeyboard/View/DQEmoticon.swift
1
1019
// // DQEmoticon.swift // SinaWeibo // // Created by admin on 2016/10/8. // Copyright © 2016年 Derrick_Qin. All rights reserved. // import UIKit class DQEmoticon: NSObject, NSCoding { //想服务器发送的表情文字 var chs: String? //本地用来匹配文字 显示对应的图片 var png: String? //0 就是图片表情 1 就是Emoji表情 var type: Int = 0 //Emoji表情的十六进制的字符串 var code: String? { didSet{ emojiString = ((code ?? "") as NSString).emoji() } } //图片路径:只有图片表情才有,emoji没有 var imagePath: String? var emojiString: String? override init() { super.init() } required init?(coder aDecoder: NSCoder) { //给对象发送消息 ,需要确保对象已经被实例化 super.init() self.yy_modelInit(with: aDecoder) } func encode(with aCoder: NSCoder) { yy_modelEncode(with: aCoder) } }
mit
NunoAlexandre/broccoli_mobile
ios/Carthage/Checkouts/Eureka/Source/Rows/PickerInlineRow.swift
2
3187
// PickerInlineRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // 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 Foundation open class PickerInlineCell<T: Equatable> : Cell<T>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func setup() { super.setup() accessoryType = .none editingAccessoryType = .none } open override func update() { super.update() selectionStyle = row.isDisabled ? .none : .default } open override func didSelect() { super.didSelect() row.deselect() } } //MARK: PickerInlineRow open class _PickerInlineRow<T> : Row<PickerInlineCell<T>>, NoValueDisplayTextConformance where T: Equatable { public typealias InlineRow = PickerRow<T> open var options = [T]() open var noValueDisplayText: String? required public init(tag: String?) { super.init(tag: tag) } } /// A generic inline row where the user can pick an option from a picker view which shows and hides itself automatically public final class PickerInlineRow<T> : _PickerInlineRow<T>, RowType, InlineRowType where T: Equatable { required public init(tag: String?) { super.init(tag: tag) onExpandInlineRow { cell, row, _ in let color = cell.detailTextLabel?.textColor row.onCollapseInlineRow { cell, _, _ in cell.detailTextLabel?.textColor = color } cell.detailTextLabel?.textColor = cell.tintColor } } public override func customDidSelect() { super.customDidSelect() if !isDisabled { toggleInlineRow() } } public func setupInlineRow(_ inlineRow: InlineRow) { inlineRow.options = self.options inlineRow.displayValueFor = self.displayValueFor } }
mit
chrisdoc/hubber
hubberTests/GithubApiClientTests.swift
1
1563
import XCTest @testable import Hubber class GithubApiClientTests: XCTestCase { var sut: GitHubApi! override func setUp() { super.setUp() sut = GitHubApiClient() } func testSearchingUsersWithName_chrisdoc() { let userExp = expectation(description: "User completion") sut.searchUsers("chrisdoc") { (users, error) in if let unwrappedUsers = users { XCTAssertEqual(unwrappedUsers.count, 6) XCTAssertEqual(unwrappedUsers[0].username, "chrisdoc") } else { XCTFail("No users have been returned") } userExp.fulfill() } waitForExpectations(timeout: 5) { error in if let error = error { XCTFail("Error: \(error.localizedDescription)") } } } func testSearchingRepositoriesWithName_hubber() { let userExp = expectation(description: "User completion") sut.searchRepositories("react") { (repositories, error) in if let repos = repositories { XCTAssertGreaterThanOrEqual(repos.count, 27) XCTAssertEqual(repos[25].name, "react-tutorial") } else { XCTFail("No users have been returned") } userExp.fulfill() } waitForExpectations(timeout: 5) { error in if let error = error { XCTFail("Error: \(error.localizedDescription)") } } } }
mit
xglofter/PicturePicker
PicturePicker/AlbumTableViewController.swift
1
6340
// // AlbumTableViewController.swift // // Created by Richard on 2017/4/20. // Copyright © 2017年 Richard. All rights reserved. // import UIKit import Photos open class AlbumTableViewController: UITableViewController { public enum AlbumSection: Int { case allPhotos = 0 case otherAlbumPhotos static let count = 2 } fileprivate(set) var allPhotos: PHFetchResult<PHAsset>! fileprivate(set) lazy var otherAlbumTitles = [String]() fileprivate(set) lazy var otherAlbumPhotos = [PHFetchResult<PHAsset>]() fileprivate(set) var isFirstEnter = true // MARK: - Lifecycle public init(with allPhotos: PHFetchResult<PHAsset>) { super.init(nibName: nil, bundle: nil) self.allPhotos = allPhotos } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { super.viewDidLoad() setup() fetchAlbums() // 监测系统相册增加 PHPhotoLibrary.shared().register(self) // 注册cell tableView.register(AlbumTableViewCell.self, forCellReuseIdentifier: AlbumTableViewCell.cellIdentity) tableView.separatorStyle = .none } // override open func viewDidAppear(_ animated: Bool) { // super.viewDidAppear(animated) // // if isFirstEnter { // isFirstEnter = false // let gridVC = PhotosGridViewController(with: allPhotos) // gridVC.title = "所有照片" // self.navigationController?.pushViewController(gridVC, animated: true) // } // } // MARK: - Table view data source override open func numberOfSections(in tableView: UITableView) -> Int { return AlbumSection.count } override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch AlbumSection(rawValue: section)! { case .allPhotos: return 1 case .otherAlbumPhotos: return otherAlbumPhotos.count } } override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return PickerConfig.albumCellHeight } override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AlbumTableViewCell", for: indexPath) as! AlbumTableViewCell cell.accessoryType = .disclosureIndicator switch AlbumSection(rawValue: indexPath.section)! { case .allPhotos: cell.setAlbumPreview(asset: allPhotos.firstObject) cell.setAlbumTitle(title: "所有照片", fileCount: allPhotos.count) case .otherAlbumPhotos: let photoAssets = otherAlbumPhotos[indexPath.row] let asset = photoAssets.firstObject cell.setAlbumPreview(asset: asset) cell.setAlbumTitle(title: otherAlbumTitles[indexPath.row], fileCount: photoAssets.count) } return cell } override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch AlbumSection.init(rawValue: indexPath.section)! { case .allPhotos: let gridVC = PhotosGridViewController(with: allPhotos) gridVC.title = "所有照片" self.navigationController?.pushViewController(gridVC, animated: true) case .otherAlbumPhotos: let gridVC = PhotosGridViewController(with: otherAlbumPhotos[indexPath.row]) gridVC.title = otherAlbumTitles[indexPath.row] self.navigationController?.pushViewController(gridVC, animated: true) } } } // MARK: - PHPhotoLibraryChangeObserver extension AlbumTableViewController: PHPhotoLibraryChangeObserver { public func photoLibraryDidChange(_ changeInstance: PHChange) { DispatchQueue.main.sync { if let _ = changeInstance.changeDetails(for: allPhotos) { fetchAlbums() tableView?.reloadData() } } } } // MARK: - Private Function private extension AlbumTableViewController { func setup() { navigationItem.title = "照片" self.view.backgroundColor = PickerConfig.pickerBackgroundColor let cancelTitle = "取消" let barItem = UIBarButtonItem(title: cancelTitle, style: .plain, target: self, action: #selector(onDismissAction)) navigationItem.rightBarButtonItem = barItem } @objc func onDismissAction() { self.dismiss(animated: true, completion: { PickerManager.shared.endChoose(isFinish: false) }) } func fetchAlbums() { // let allPhotoOptions = PHFetchOptions() // allPhotoOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] // allPhotoOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) // allPhotos = PHAsset.fetchAssets(with: allPhotoOptions) let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: nil) let userCollections = PHCollectionList.fetchTopLevelUserCollections(with: nil) otherAlbumTitles.removeAll() otherAlbumPhotos.removeAll() func getAlbumNotEmpty(from albums: PHFetchResult<PHAssetCollection>) { let photoOptions = PHFetchOptions() photoOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] for index in 0 ..< albums.count { let collection = albums.object(at: index) let asset = PHAsset.fetchAssets(in: collection, options: photoOptions) if asset.count != 0 { self.otherAlbumTitles.append(collection.localizedTitle ?? "") self.otherAlbumPhotos.append(asset) } } } getAlbumNotEmpty(from: smartAlbums) getAlbumNotEmpty(from: userCollections as! PHFetchResult<PHAssetCollection>) print(otherAlbumPhotos.count) } }
mit
groschovskiy/firebase-for-banking-app
Demo/Pods/CircleMenu/CircleMenuLib/CircleMenu.swift
2
17367
// // CircleMenu.swift // ButtonTest // // Copyright (c) 18/01/16. Ramotion Inc. (http://ramotion.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 // MARK: helpers func Init<Type>(_ value: Type, block: (_ object: Type) -> Void) -> Type { block(value) return value } // MARK: Protocol /** * CircleMenuDelegate */ @objc public protocol CircleMenuDelegate { /** Tells the delegate the circle menu is about to draw a button for a particular index. - parameter circleMenu: The circle menu object informing the delegate of this impending event. - parameter button: A circle menu button object that circle menu is going to use when drawing the row. Don't change button.tag - parameter atIndex: An button index. */ @objc optional func circleMenu(_ circleMenu: CircleMenu, willDisplay button: UIButton, atIndex: Int) /** Tells the delegate that a specified index is about to be selected. - parameter circleMenu: A circle menu object informing the delegate about the impending selection. - parameter button: A selected circle menu button. Don't change button.tag - parameter atIndex: Selected button index */ @objc optional func circleMenu(_ circleMenu: CircleMenu, buttonWillSelected button: UIButton, atIndex: Int) /** Tells the delegate that the specified index is now selected. - parameter circleMenu: A circle menu object informing the delegate about the new index selection. - parameter button: A selected circle menu button. Don't change button.tag - parameter atIndex: Selected button index */ @objc optional func circleMenu(_ circleMenu: CircleMenu, buttonDidSelected button: UIButton, atIndex: Int) /** Tells the delegate that the menu was collapsed - the cancel action. - parameter circleMenu: A circle menu object informing the delegate about the new index selection. */ @objc optional func menuCollapsed(_ circleMenu: CircleMenu) } // MARK: CircleMenu /// A Button object with pop ups buttons open class CircleMenu: UIButton { // MARK: properties /// Buttons count @IBInspectable open var buttonsCount: Int = 3 /// Circle animation duration @IBInspectable open var duration: Double = 2 /// Distance between center button and buttons @IBInspectable open var distance: Float = 100 /// Delay between show buttons @IBInspectable open var showDelay: Double = 0 /// The object that acts as the delegate of the circle menu. @IBOutlet weak open var delegate: AnyObject? //CircleMenuDelegate? var buttons: [UIButton]? weak var platform: UIView? fileprivate var customNormalIconView: UIImageView? fileprivate var customSelectedIconView: UIImageView? /** Initializes and returns a circle menu object. - parameter frame: A rectangle specifying the initial location and size of the circle menu in its superview’€™s coordinates. - parameter normalIcon: The image to use for the specified normal state. - parameter selectedIcon: The image to use for the specified selected state. - parameter buttonsCount: The number of buttons. - parameter duration: The duration, in seconds, of the animation. - parameter distance: Distance between center button and sub buttons. - returns: A newly created circle menu. */ public init(frame: CGRect, normalIcon: String?, selectedIcon: String?, buttonsCount: Int = 3, duration: Double = 2, distance: Float = 100) { super.init(frame: frame) if let icon = normalIcon { setImage(UIImage(named: icon), for: UIControlState()) } if let icon = selectedIcon { setImage(UIImage(named: icon), for: .selected) } self.buttonsCount = buttonsCount self.duration = duration self.distance = distance commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { addActions() customNormalIconView = addCustomImageView(state: UIControlState()) customSelectedIconView = addCustomImageView(state: .selected) if customSelectedIconView != nil { customSelectedIconView?.alpha = 0 } setImage(UIImage(), for: UIControlState()) setImage(UIImage(), for: .selected) } // MARK: methods /** Hide button - parameter duration: The duration, in seconds, of the animation. - parameter hideDelay: The time to delay, in seconds. */ open func hideButtons(_ duration: Double, hideDelay: Double = 0) { if buttons == nil { return } buttonsAnimationIsShow(isShow: false, duration: duration, hideDelay: hideDelay) tapBounceAnimation() tapRotatedAnimation(0.3, isSelected: false) } /** Check is sub buttons showed */ open func buttonsIsShown() -> Bool { guard let buttons = self.buttons else { return false } for button in buttons { if button.alpha == 0 { return false } } return true } // MARK: create fileprivate func createButtons(platform: UIView) -> [UIButton] { var buttons = [UIButton]() let step: Float = 360.0 / Float(self.buttonsCount) for index in 0..<self.buttonsCount { let angle: Float = Float(index) * step let distance = Float(self.bounds.size.height/2.0) let button = Init(CircleMenuButton(size: self.bounds.size, platform: platform, distance:distance, angle: angle)) { $0.tag = index $0.addTarget(self, action: #selector(CircleMenu.buttonHandler(_:)), for: UIControlEvents.touchUpInside) $0.alpha = 0 } buttons.append(button) } return buttons } fileprivate func addCustomImageView(state: UIControlState) -> UIImageView? { guard let image = image(for: state) else { return nil } let iconView = Init(UIImageView(image: image)) { $0.translatesAutoresizingMaskIntoConstraints = false $0.contentMode = .center $0.isUserInteractionEnabled = false } addSubview(iconView) // added constraints iconView.addConstraint(NSLayoutConstraint(item: iconView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: bounds.size.height)) iconView.addConstraint(NSLayoutConstraint(item: iconView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: bounds.size.width)) addConstraint(NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: iconView, attribute: .centerX, multiplier: 1, constant:0)) addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: iconView, attribute: .centerY, multiplier: 1, constant:0)) return iconView } fileprivate func createPlatform() -> UIView { let platform = Init(UIView(frame: .zero)) { $0.backgroundColor = .clear $0.translatesAutoresizingMaskIntoConstraints = false } superview?.insertSubview(platform, belowSubview: self) // constraints let sizeConstraints = [NSLayoutAttribute.width, .height].map { NSLayoutConstraint(item: platform, attribute: $0, relatedBy: .equal, toItem: nil, attribute: $0, multiplier: 1, constant: CGFloat(distance * Float(2.0))) } platform.addConstraints(sizeConstraints) let centerConstraints = [NSLayoutAttribute.centerX, .centerY].map { NSLayoutConstraint(item: self, attribute: $0, relatedBy: .equal, toItem: platform, attribute: $0, multiplier: 1, constant:0) } superview?.addConstraints(centerConstraints) return platform } // MARK: configure fileprivate func addActions() { self.addTarget(self, action: #selector(CircleMenu.onTap), for: UIControlEvents.touchUpInside) } // MARK: actions func onTap() { if buttonsIsShown() == false { let platform = createPlatform() buttons = createButtons(platform: platform) self.platform = platform } let isShow = !buttonsIsShown() let duration = isShow ? 0.5 : 0.2 buttonsAnimationIsShow(isShow: isShow, duration: duration) tapBounceAnimation() tapRotatedAnimation(0.3, isSelected: isShow) } func buttonHandler(_ sender: CircleMenuButton) { guard let platform = self.platform else { return } delegate?.circleMenu?(self, buttonWillSelected: sender, atIndex: sender.tag) let circle = CircleMenuLoader(radius: CGFloat(distance), strokeWidth: bounds.size.height, platform: platform, color: sender.backgroundColor) if let container = sender.container { // rotation animation sender.rotationAnimation(container.angleZ + 360, duration: duration) container.superview?.bringSubview(toFront: container) } if let buttons = buttons { circle.fillAnimation(duration, startAngle: -90 + Float(360 / buttons.count) * Float(sender.tag)) { [weak self] _ in self?.buttons?.forEach { $0.alpha = 0 } } circle.hideAnimation(0.5, delay: duration) { [weak self] _ in if self?.platform?.superview != nil { self?.platform?.removeFromSuperview() } } hideCenterButton(duration: 0.3) showCenterButton(duration: 0.525, delay: duration) if customNormalIconView != nil && customSelectedIconView != nil { DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: { self.delegate?.circleMenu?(self, buttonDidSelected: sender, atIndex: sender.tag) }) } } } // MARK: animations fileprivate func buttonsAnimationIsShow(isShow: Bool, duration: Double, hideDelay: Double = 0) { guard let buttons = self.buttons else { return } let step: Float = 360.0 / Float(self.buttonsCount) for index in 0..<self.buttonsCount { guard case let button as CircleMenuButton = buttons[index] else { continue } let angle: Float = Float(index) * step if isShow == true { delegate?.circleMenu?(self, willDisplay: button, atIndex: index) button.rotatedZ(angle: angle, animated: false, delay: Double(index) * showDelay) button.showAnimation(distance: distance, duration: duration, delay: Double(index) * showDelay) } else { button.hideAnimation( distance: Float(self.bounds.size.height / 2.0), duration: duration, delay: hideDelay) self.delegate?.menuCollapsed?(self) } } if isShow == false { // hide buttons and remove self.buttons = nil } } fileprivate func tapBounceAnimation() { self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 5, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: nil) } fileprivate func tapRotatedAnimation(_ duration: Float, isSelected: Bool) { let addAnimations: (_ view: UIImageView, _ isShow: Bool) -> () = { (view, isShow) in var toAngle: Float = 180.0 var fromAngle: Float = 0 var fromScale = 1.0 var toScale = 0.2 var fromOpacity = 1 var toOpacity = 0 if isShow == true { toAngle = 0 fromAngle = -180 fromScale = 0.2 toScale = 1.0 fromOpacity = 0 toOpacity = 1 } let rotation = Init(CABasicAnimation(keyPath: "transform.rotation")) { $0.duration = TimeInterval(duration) $0.toValue = (toAngle.degrees) $0.fromValue = (fromAngle.degrees) $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } let fade = Init(CABasicAnimation(keyPath: "opacity")) { $0.duration = TimeInterval(duration) $0.fromValue = fromOpacity $0.toValue = toOpacity $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) $0.fillMode = kCAFillModeForwards $0.isRemovedOnCompletion = false } let scale = Init(CABasicAnimation(keyPath: "transform.scale")) { $0.duration = TimeInterval(duration) $0.toValue = toScale $0.fromValue = fromScale $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } view.layer.add(rotation, forKey: nil) view.layer.add(fade, forKey: nil) view.layer.add(scale, forKey: nil) } if let customNormalIconView = self.customNormalIconView { addAnimations(customNormalIconView, !isSelected) } if let customSelectedIconView = self.customSelectedIconView { addAnimations(customSelectedIconView, isSelected) } self.isSelected = isSelected self.alpha = isSelected ? 0.3 : 1 } fileprivate func hideCenterButton(duration: Double, delay: Double = 0) { UIView.animate( withDuration: TimeInterval(duration), delay: TimeInterval(delay), options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 0.001, y: 0.001) }, completion: nil) } fileprivate func showCenterButton(duration: Float, delay: Double) { UIView.animate( withDuration: TimeInterval(duration), delay: TimeInterval(delay), usingSpringWithDamping: 0.78, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1, y: 1) self.alpha = 1 }, completion: nil) let rotation = Init(CASpringAnimation(keyPath: "transform.rotation")) { $0.duration = TimeInterval(1.5) $0.toValue = (0) $0.fromValue = (Float(-180).degrees) $0.damping = 10 $0.initialVelocity = 0 $0.beginTime = CACurrentMediaTime() + delay } let fade = Init(CABasicAnimation(keyPath: "opacity")) { $0.duration = TimeInterval(0.01) $0.toValue = 0 $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) $0.fillMode = kCAFillModeForwards $0.isRemovedOnCompletion = false $0.beginTime = CACurrentMediaTime() + delay } let show = Init(CABasicAnimation(keyPath: "opacity")) { $0.duration = TimeInterval(duration) $0.toValue = 1 $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) $0.fillMode = kCAFillModeForwards $0.isRemovedOnCompletion = false $0.beginTime = CACurrentMediaTime() + delay } customNormalIconView?.layer.add(rotation, forKey: nil) customNormalIconView?.layer.add(show, forKey: nil) customSelectedIconView?.layer.add(fade, forKey: nil) } } // MARK: extension internal extension Float { var radians: Float { return self * (Float(180) / Float(M_PI)) } var degrees: Float { return self * Float(M_PI) / 180.0 } } internal extension UIView { var angleZ: Float { return atan2(Float(self.transform.b), Float(self.transform.a)).radians } }
apache-2.0
TinyCrayon/TinyCrayon-iOS-SDK
Examples/swift/TCMaskCustomization/TCMaskCustomization/ViewController.swift
1
3538
// // The MIT License // // Copyright (C) 2016 TinyCrayon. // // 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 TCMask class ViewController: UIViewController, TCMaskViewDelegate { @IBOutlet weak var imageView: UIImageView! override func viewDidAppear(_ animated: Bool) { if (imageView.image == nil) { presentTCMaskView() } } @IBAction func editButtonTapped(_ sender: Any) { presentTCMaskView() } func presentTCMaskView() { let image = UIImage(named: "Balloon.JPEG")! let maskView = TCMaskView(image: image) maskView.delegate = self // Change status bar style maskView.statusBarStyle = UIStatusBarStyle.lightContent // Change UI components style maskView.topBar.backgroundColor = UIColor(white: 0.1, alpha: 1) maskView.topBar.tintColor = UIColor.white maskView.imageView.backgroundColor = UIColor(white: 0.2, alpha: 1) maskView.bottomBar.backgroundColor = UIColor(white: 0.1, alpha: 1) maskView.bottomBar.tintColor = UIColor.white maskView.bottomBar.textColor = UIColor.white maskView.settingView.backgroundColor = UIColor(white: 0.8, alpha: 0.9) maskView.settingView.textColor = UIColor(white: 0.33, alpha: 1) // Create a customized view mode with gray scale image let grayScaleImage = image.convertToGrayScaleNoAlpha() let viewMode = TCMaskViewMode(foregroundImage: grayScaleImage, backgroundImage: nil, isInverted: true) // set customized viewMode to be the only view mode in TCMaskView maskView.viewModes = [viewMode] maskView.presentFrom(rootViewController: self, animated: true) } func tcMaskViewDidComplete(mask: TCMask, image: UIImage) { imageView.image = mask.cutout(image: image, resize: true) } } extension UIImage { func convertToGrayScaleNoAlpha() -> UIImage { let colorSpace = CGColorSpaceCreateDeviceGray(); let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue) let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) context?.draw(self.cgImage!, in: CGRect(origin: CGPoint(), size: size)) return UIImage(cgImage: context!.makeImage()!) } }
mit
jinSasaki/in-app-purchase
Tests/ProductProviderTests.swift
1
3838
// // ProductProviderTests.swift // InAppPurchase // // Created by Jin Sasaki on 2017/04/06. // Copyright © 2017年 Jin Sasaki. All rights reserved. // import XCTest @testable import InAppPurchase import StoreKit class ProductProviderTests: XCTestCase { let provider = ProductProvider() func testMakeRequest() { let request = provider.makeRequest(productIdentifiers: ["PRODUCT_001"], requestId: "REQUEST_001") XCTAssertTrue(request.delegate === provider) XCTAssertEqual(request.id, "REQUEST_001") } func testFetch() { let expectation = self.expectation() let request = StubProductsRequest(startHandler: { expectation.fulfill() }) provider.fetch(request: request) { _ in } wait(for: [expectation], timeout: 1) } func testFetchWithRequestWhereSuccess() { let request = provider.makeRequest(productIdentifiers: ["PRODUCT_001"], requestId: "REQUEST_001") let expectation = self.expectation() provider.fetch(request: request) { (result) in switch result { case .success(let products): XCTAssertEqual(products.count, 1) XCTAssertEqual(products.first?.productIdentifier, "PRODUCT_001") case .failure: XCTFail() } expectation.fulfill() } let response = StubProductsResponse(products: [StubProduct(productIdentifier: "PRODUCT_001")], invalidProductIdentifiers: []) provider.productsRequest(request, didReceive: response) wait(for: [expectation], timeout: 1) } func testFetchWithRequestWhereInvalidIds() { let request = provider.makeRequest(productIdentifiers: ["INVALID_PRODUCT_001"], requestId: "REQUEST_001") let expectation = self.expectation() provider.fetch(request: request) { (result) in switch result { case .success: XCTFail() case .failure(let error): switch error { case .invalid(let productIds): XCTAssertEqual(productIds.count, 1) XCTAssertEqual(productIds.first, "INVALID_PRODUCT_001") default: XCTFail() } } expectation.fulfill() } let response = StubProductsResponse(products: [StubProduct(productIdentifier: "PRODUCT_001")], invalidProductIdentifiers: ["INVALID_PRODUCT_001"]) provider.productsRequest(request, didReceive: response) wait(for: [expectation], timeout: 1) } func testFetchWithRequestWhereRequestFailure() { let request = provider.makeRequest(productIdentifiers: ["INVALID_PRODUCT_001"], requestId: "REQUEST_001") let expectation = self.expectation() provider.fetch(request: request) { (result) in switch result { case .success: XCTFail() case .failure(let error): if case let .with(err) = error { let err = err as NSError XCTAssertEqual(err.domain, "test") XCTAssertEqual(err.code, 500) } else { XCTFail() } } expectation.fulfill() } let error = NSError(domain: "test", code: 500, userInfo: nil) provider.request(request, didFailWithError: error) wait(for: [expectation], timeout: 1) } // MARK: - SKRequest extension func testRequestId() { let request = SKRequest() XCTAssertEqual(request.id, "") request.id = "REQUEST_001" XCTAssertEqual(request.id, "REQUEST_001") request.id = "REQUEST_002" XCTAssertEqual(request.id, "REQUEST_002") } }
mit
kiritantan/iQONTweetDisplay
iQONTweetDisplay/Tweet.swift
1
1121
// // Tweet.swift // iQONTweetDisplay // // Created by kiri on 2016/06/14. // Copyright © 2016年 kiri. All rights reserved. // import UIKit import SwiftyJSON class Tweet { let fullname: String let username: String let tweetText: String let timeStamp: String var avatar = UIImage() init(jsonData: JSON) { self.fullname = jsonData["user"]["name"].stringValue self.username = jsonData["user"]["screen_name"].stringValue self.tweetText = jsonData["text"].stringValue self.timeStamp = jsonData["created_at"].stringValue self.avatar = downloadImageFromURL(jsonData["user"]["profile_image_url_https"].stringValue) } private func downloadImageFromURL(imageURLString: String) -> UIImage { let url = NSURL(string: imageURLString.stringByReplacingOccurrencesOfString("\\", withString: "")) let imageData = NSData(contentsOfURL: url!) var image = UIImage() if let data = imageData { if let img = UIImage(data: data) { image = img } } return image; } }
mit
BelledonneCommunications/linphone-iphone
Classes/Swift/Extensions/LinphoneCore/CoreExtensions.swift
1
1332
/* * Copyright (c) 2010-2020 Belledonne Communications SARL. * * This file is part of linphone-iphone * * 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 linphonesw extension Core { static func get() -> Core { return CallManager.instance().lc! } func showSwitchCameraButton() -> Bool { return videoDevicesList.count > 2 // Count StaticImage camera } func toggleCamera() { Log.i("[Core] Current camera device is \(videoDevice)") var switched = false videoDevicesList.forEach { if (!switched && $0 != videoDevice && $0 != "StaticImage: Static picture") { Log.i("[Core] New camera device will be \($0)") try?setVideodevice(newValue: $0) switched = true } } } }
gpl-3.0
ben-ng/swift
stdlib/private/StdlibCollectionUnittest/RangeSelection.swift
1
3344
//===--- RangeSelection.swift ---------------------------------------------===// // // 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import StdlibUnittest public enum RangeSelection { case emptyRange case leftEdge case rightEdge case middle case leftHalf case rightHalf case full case offsets(Int, Int) public var isEmpty: Bool { switch self { case .emptyRange: return true default: return false } } public func range<C : Collection>(in c: C) -> Range<C.Index> { switch self { case .emptyRange: return c.endIndex..<c.endIndex case .leftEdge: return c.startIndex..<c.startIndex case .rightEdge: return c.endIndex..<c.endIndex case .middle: let start = c.index(c.startIndex, offsetBy: c.count / 4) let end = c.index(c.startIndex, offsetBy: 3 * c.count / 4 + 1) return start..<end case .leftHalf: let start = c.startIndex let end = c.index(start, offsetBy: c.count / 2) return start..<end case .rightHalf: let start = c.index(c.startIndex, offsetBy: c.count / 2) let end = c.endIndex return start..<end case .full: return c.startIndex..<c.endIndex case let .offsets(lowerBound, upperBound): let start = c.index(c.startIndex, offsetBy: numericCast(lowerBound)) let end = c.index(c.startIndex, offsetBy: numericCast(upperBound)) return start..<end } } public func countableRange<C : Collection>(in c: C) -> CountableRange<C.Index> { return CountableRange(range(in: c)) } public func closedRange<C : Collection>(in c: C) -> ClosedRange<C.Index> { switch self { case .emptyRange: fatalError("Closed range cannot be empty") case .leftEdge: return c.startIndex...c.startIndex case .rightEdge: let beforeEnd = c.index(c.startIndex, offsetBy: c.count - 1) return beforeEnd...beforeEnd case .middle: let start = c.index(c.startIndex, offsetBy: c.count / 4) let end = c.index(c.startIndex, offsetBy: 3 * c.count / 4) return start...end case .leftHalf: let start = c.startIndex let end = c.index(start, offsetBy: c.count / 2 - 1) return start...end case .rightHalf: let start = c.index(c.startIndex, offsetBy: c.count / 2) let beforeEnd = c.index(c.startIndex, offsetBy: c.count - 1) return start...beforeEnd case .full: let beforeEnd = c.index(c.startIndex, offsetBy: c.count - 1) return c.startIndex...beforeEnd case let .offsets(lowerBound, upperBound): let start = c.index(c.startIndex, offsetBy: numericCast(lowerBound)) let end = c.index(c.startIndex, offsetBy: numericCast(upperBound)) return start...end } } public func countableClosedRange<C : Collection>(in c: C) -> CountableClosedRange<C.Index> { return CountableClosedRange(closedRange(in: c)) } }
apache-2.0
relayr/apple-iot-smartphone
IoT/ios/sources/DeviceController.swift
1
3369
import UIKit /// View Controller managing the "device data" screen. /// /// It is in charge of arranging the meaning cells, and it manages the display shared objects. class DeviceController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { /// The cell identifying each meaning graph. private enum CellID : String { case SimpleGraph = "SimpleGraphCellID" case Map = "MapCellID" } /// Collection view holding the meaning cells @IBOutlet private(set) weak var collectionView : UICollectionView! /// The Metal device in charge of rendering all the graph in this collection controller. static let device = MTLCreateSystemDefaultDevice()! /// Inmutable instance containing reusable data for rendering graphs (of any type). let sharedRenderState : GraphRenderState = GraphRenderState(withDevice: DeviceController.device, numTrianglesPerDot: 20)! /// Instance containing all the data to be shown on the display. let sharedRenderData : GraphRenderData = GraphRenderData(withDevice: DeviceController.device, supportedMeanings: [.Location, .Accelerometer, .Gyroscope, .Magnetometer]) // MARK: UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 2 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if indexPath.row == 0 { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellID.SimpleGraph.rawValue, forIndexPath: indexPath) as! SimpleGraphCellView cell.graphView.renderData(withState: sharedRenderState, samplerType: .Accelerometer, graphMeaning: sharedRenderData[.Accelerometer]!) return cell } else { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellID.Map.rawValue, forIndexPath: indexPath) as! MapCellView return cell } } // MARK: UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let bounds = self.collectionView.bounds return CGSize(width: bounds.width, height: 0.4*bounds.height) } // MARK: UIViewController override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { sharedRenderState.displayRefresh.paused = false } override func viewDidDisappear(animated: Bool) { sharedRenderState.displayRefresh.paused = true } } class SimpleGraphCellView : UICollectionViewCell { @IBOutlet private(set) weak var meaningLabel : UILabel! @IBOutlet private(set) weak var settingsIconView : UIView! @IBOutlet private(set) weak var graphView : GraphView! } class MapCellView : UICollectionViewCell { @IBOutlet private(set) weak var meaningLabel : UILabel! @IBOutlet private(set) weak var settingsIconView : UIView! @IBOutlet private(set) weak var mapView : UIImageView! }
mit
cuzv/Popover
Sample/AppDelegate.swift
1
2162
// // AppDelegate.swift // Sample // // Created by Roy Shaw on 3/18/16. // Copyright © 2016 Red Rain. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } }
mit
rnystrom/GitHawk
FreetimeWatch Extension/Utility/V3Repository+HashableEquatable.swift
1
623
// // V3Repository+HashableEquatable.swift // FreetimeWatch Extension // // Created by Ryan Nystrom on 4/28/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import Foundation import GitHubAPI extension V3Repository: Hashable, Equatable { public func hash(into hasher: inout Hasher) { hasher.combine(fullName.hashValue) } public static func ==(lhs: V3Repository, rhs: V3Repository) -> Bool { // a little bit lazy, but fast & cheap for the watch app's purpose return lhs.id == rhs.id && lhs.fork == rhs.fork && lhs.isPrivate == rhs.isPrivate } }
mit
vrutberg/VRPicker
VRPicker/Classes/PickerItemCollectionViewCell.swift
1
473
// // PickerItemCollectionViewCell.swift // VRPicker // // Created by Viktor Rutberg on 2017-10-16. // import Foundation class PickerItemCollectionViewCell: UICollectionViewCell { @IBOutlet var label: UILabel! func update(model: Model) { label.text = model.text label.font = model.font label.textColor = model.fontColor } struct Model { let text: String let font: UIFont let fontColor: UIColor } }
mit
buscarini/JMSSwiftParse
iOS Example/iOS ExampleTests/iOS_ExampleTests.swift
1
943
// // iOS_ExampleTests.swift // iOS ExampleTests // // Created by Jose Manuel Sánchez Peñarroja on 10/11/14. // Copyright (c) 2014 José Manuel Sánchez. All rights reserved. // import UIKit import XCTest class iOS_ExampleTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
frootloops/swift
test/Parse/recovery.swift
1
31387
// RUN: %target-typecheck-verify-swift //===--- Helper types used in this file. protocol FooProtocol {} //===--- Tests. func garbage() -> () { var a : Int ] this line is invalid, but we will stop at the keyword below... // expected-error{{expected expression}} return a + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } func moreGarbage() -> () { ) this line is invalid, but we will stop at the declaration... // expected-error{{expected expression}} func a() -> Int { return 4 } return a() + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } class Container<T> { func exists() -> Bool { return true } } func useContainer() -> () { var a : Container<not a type [skip this greater: >] >, b : Int // expected-error{{expected '>' to complete generic argument list}} expected-note{{to match this opening '<'}} b = 5 // no-warning a.exists() } @xyz class BadAttributes { // expected-error{{unknown attribute 'xyz'}} func exists() -> Bool { return true } } func test(a: BadAttributes) -> () { // expected-note * {{did you mean 'test'?}} _ = a.exists() // no-warning } // Here is an extra random close-brace! } // expected-error{{extraneous '}' at top level}} {{1-3=}} //===--- Recovery for braced blocks. func braceStmt1() { { braceStmt1(); } // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} } func braceStmt2() { { () in braceStmt2(); } // expected-error {{closure expression is unused}} } func braceStmt3() { { // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} undefinedIdentifier {} // expected-error {{use of unresolved identifier 'undefinedIdentifier'}} } } //===--- Recovery for misplaced 'static'. static func toplevelStaticFunc() {} // expected-error {{static methods may only be declared on a type}} {{1-8=}} static struct StaticStruct {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static class StaticClass {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static protocol StaticProtocol {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static typealias StaticTypealias = Int // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} class ClassWithStaticDecls { class var a = 42 // expected-error {{class stored properties not supported}} } //===--- Recovery for missing controlling expression in statements. func missingControllingExprInIf() { if // expected-error {{expected expression, var, or let in 'if' condition}} if { // expected-error {{missing condition in an 'if' statement}} } if // expected-error {{missing condition in an 'if' statement}} { } if true { } else if { // expected-error {{missing condition in an 'if' statement}} } // It is debatable if we should do recovery here and parse { true } as the // body, but the error message should be sensible. if { true } { // expected-error {{missing condition in an 'if' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{14-14=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{15-15=do }} expected-warning {{boolean literal is unused}} } if { true }() { // expected-error {{missing condition in an 'if' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{17-17=do }} expected-warning {{boolean literal is unused}} } // <rdar://problem/18940198> if { { } } // expected-error{{missing condition in an 'if' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{8-8=do }} } func missingControllingExprInWhile() { while // expected-error {{expected expression, var, or let in 'while' condition}} while { // expected-error {{missing condition in a 'while' statement}} } while // expected-error {{missing condition in a 'while' statement}} { } // It is debatable if we should do recovery here and parse { true } as the // body, but the error message should be sensible. while { true } { // expected-error {{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{17-17=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{18-18=do }} expected-warning {{boolean literal is unused}} } while { true }() { // expected-error {{missing condition in a 'while' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{20-20=do }} expected-warning {{boolean literal is unused}} } // <rdar://problem/18940198> while { { } } // expected-error{{missing condition in a 'while' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{11-11=do }} } func missingControllingExprInRepeatWhile() { repeat { } while // expected-error {{missing condition in a 'while' statement}} { // expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} missingControllingExprInRepeatWhile(); } repeat { } while { true }() // expected-error{{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{10-10=;}} expected-warning {{result of call is unused, but produces 'Bool'}} } // SR-165 func missingWhileInRepeat() { repeat { } // expected-error {{expected 'while' after body of 'repeat' statement}} } func acceptsClosure<T>(t: T) -> Bool { return true } func missingControllingExprInFor() { for ; { // expected-error {{C-style for statement has been removed in Swift 3}} } for ; // expected-error {{C-style for statement has been removed in Swift 3}} { } for ; true { // expected-error {{C-style for statement has been removed in Swift 3}} } for var i = 0; true { // expected-error {{C-style for statement has been removed in Swift 3}} i += 1 } } func missingControllingExprInForEach() { // expected-error @+3 {{expected pattern}} // expected-error @+2 {{expected Sequence expression for for-each loop}} // expected-error @+1 {{expected '{' to start the body of for-each loop}} for // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for { } // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for { } // expected-error @+2 {{expected 'in' after for-each pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for i { } // expected-error @+2 {{expected 'in' after for-each pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for var i { } // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for in { } // expected-error @+1 {{expected pattern}} for 0..<12 { } // expected-error @+3 {{expected pattern}} // expected-error @+2 {{expected Sequence expression for for-each loop}} // expected-error @+1 {{expected '{' to start the body of for-each loop}} for for in { } for i in { // expected-error {{expected Sequence expression for for-each loop}} } // The #if block is used to provide a scope for the for stmt to force it to end // where necessary to provoke the crash. #if true // <rdar://problem/21679557> compiler crashes on "for{{" // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for{{ // expected-note 2 {{to match this opening '{'}} #endif // expected-error {{expected '}' at end of closure}} expected-error {{expected '}' at end of brace statement}} #if true // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for{ var x = 42 } #endif // SR-5943 struct User { let name: String? } let users = [User]() for user in users whe { // expected-error {{expected '{' to start the body of for-each loop}} if let name = user.name { let key = "\(name)" } } for // expected-error {{expected pattern}} expected-error {{Sequence expression for for-each loop}} ; // expected-error {{expected '{' to start the body of for-each loop}} } func missingControllingExprInSwitch() { switch // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} switch { // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} } switch // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} { } switch { // expected-error {{expected expression in 'switch' statement}} case _: return } switch { // expected-error {{expected expression in 'switch' statement}} case Int: return // expected-error {{'is' keyword required to pattern match against type name}} {{10-10=is }} case _: return } switch { 42 } { // expected-error {{expected expression in 'switch' statement}} expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error{{consecutive statements on a line must be separated by ';'}} {{16-16=;}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{17-17=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}} } switch { 42 }() { // expected-error {{expected expression in 'switch' statement}} expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{19-19=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}} } } //===--- Recovery for missing braces in nominal type decls. struct NoBracesStruct1() // expected-error {{expected '{' in struct}} enum NoBracesUnion1() // expected-error {{expected '{' in enum}} class NoBracesClass1() // expected-error {{expected '{' in class}} protocol NoBracesProtocol1() // expected-error {{expected '{' in protocol type}} extension NoBracesStruct1() // expected-error {{expected '{' in extension}} struct NoBracesStruct2 // expected-error {{expected '{' in struct}} enum NoBracesUnion2 // expected-error {{expected '{' in enum}} class NoBracesClass2 // expected-error {{expected '{' in class}} protocol NoBracesProtocol2 // expected-error {{expected '{' in protocol type}} extension NoBracesStruct2 // expected-error {{expected '{' in extension}} //===--- Recovery for multiple identifiers in decls protocol Multi ident {} // expected-error @-1 {{found an unexpected second identifier in protocol declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{10-21=Multiident}} // expected-note @-3 {{join the identifiers together with camel-case}} {{10-21=MultiIdent}} class CCC CCC<T> {} // expected-error @-1 {{found an unexpected second identifier in class declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{7-14=CCCCCC}} enum EE EE<T> where T : Multi { // expected-error @-1 {{found an unexpected second identifier in enum declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{6-11=EEEE}} case a a // expected-error @-1 {{found an unexpected second identifier in enum 'case' declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{8-11=aa}} // expected-note @-3 {{join the identifiers together with camel-case}} {{8-11=aA}} case b } struct SS SS : Multi { // expected-error @-1 {{found an unexpected second identifier in struct declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{8-13=SSSS}} private var a b : Int = "" // expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{15-18=ab}} // expected-note @-3 {{join the identifiers together with camel-case}} {{15-18=aB}} // expected-error @-4 {{cannot convert value of type 'String' to specified type 'Int'}} func f() { var c d = 5 // expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{9-12=cd}} // expected-note @-3 {{join the identifiers together with camel-case}} {{9-12=cD}} // expected-warning @-4 {{initialization of variable 'c' was never used; consider replacing with assignment to '_' or removing it}} let _ = 0 } } let (efg hij, foobar) = (5, 6) // expected-error @-1 {{found an unexpected second identifier in constant declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{6-13=efghij}} // expected-note @-3 {{join the identifiers together with camel-case}} {{6-13=efgHij}} _ = foobar // OK. //===--- Recovery for parse errors in types. struct ErrorTypeInVarDecl1 { var v1 : // expected-error {{expected type}} {{11-11= <#type#>}} } struct ErrorTypeInVarDecl2 { var v1 : Int. // expected-error {{expected member name following '.'}} var v2 : Int } struct ErrorTypeInVarDecl3 { var v1 : Int< // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl4 { var v1 : Int<, // expected-error {{expected type}} {{16-16= <#type#>}} var v2 : Int } struct ErrorTypeInVarDecl5 { var v1 : Int<Int // expected-error {{expected '>' to complete generic argument list}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl6 { var v1 : Int<Int, // expected-note {{to match this opening '<'}} Int // expected-error {{expected '>' to complete generic argument list}} var v2 : Int } struct ErrorTypeInVarDecl7 { var v1 : Int<Int, // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl8 { var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl9 { var v1 : protocol // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl10 { var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl11 { var v1 : protocol<FooProtocol, // expected-error {{expected identifier for type name}} var v2 : Int } func ErrorTypeInPattern1(_: protocol<) { } // expected-error {{expected identifier for type name}} func ErrorTypeInPattern2(_: protocol<F) { } // expected-error {{expected '>' to complete protocol-constrained type}} // expected-note@-1 {{to match this opening '<'}} // expected-error@-2 {{use of undeclared type 'F'}} func ErrorTypeInPattern3(_: protocol<F,) { } // expected-error {{expected identifier for type name}} // expected-error@-1 {{use of undeclared type 'F'}} struct ErrorTypeInVarDecl12 { var v1 : FooProtocol & // expected-error{{expected identifier for type name}} var v2 : Int } struct ErrorTypeInVarDecl13 { // expected-note {{in declaration of 'ErrorTypeInVarDecl13'}} var v1 : & FooProtocol // expected-error {{expected type}} expected-error {{consecutive declarations on a line must be separated by ';'}} expected-error{{expected declaration}} var v2 : Int } struct ErrorTypeInVarDecl16 { var v1 : FooProtocol & // expected-error {{expected identifier for type name}} var v2 : Int } func ErrorTypeInPattern4(_: FooProtocol & ) { } // expected-error {{expected identifier for type name}} struct ErrorGenericParameterList1< // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}} struct ErrorGenericParameterList2<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}} expected-error {{expected '{' in struct}} struct ErrorGenericParameterList3<T, // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}} // Note: Don't move braces to a different line here. struct ErrorGenericParameterList4< // expected-error {{expected an identifier to name generic parameter}} { } // Note: Don't move braces to a different line here. struct ErrorGenericParameterList5<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}} { } // Note: Don't move braces to a different line here. struct ErrorGenericParameterList6<T, // expected-error {{expected an identifier to name generic parameter}} { } struct ErrorTypeInVarDeclFunctionType1 { var v1 : () -> // expected-error {{expected type for function result}} var v2 : Int } struct ErrorTypeInVarDeclArrayType1 { // expected-note{{in declaration of 'ErrorTypeInVarDeclArrayType1'}} var v1 : Int[+] // expected-error {{expected declaration}} expected-error {{consecutive declarations on a line must be separated by ';'}} // expected-error @-1 {{expected expression after unary operator}} // expected-error @-2 {{expected expression}} var v2 : Int } struct ErrorTypeInVarDeclArrayType2 { var v1 : Int[+ // expected-error {{unary operator cannot be separated from its operand}} var v2 : Int // expected-error {{expected expression}} } struct ErrorTypeInVarDeclArrayType3 { var v1 : Int[ ; // expected-error {{expected expression}} var v2 : Int } struct ErrorTypeInVarDeclArrayType4 { var v1 : Int[1 // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} } struct ErrorInFunctionSignatureResultArrayType1 { func foo() -> Int[ { // expected-error {{expected '{' in body of function declaration}} return [0] } } struct ErrorInFunctionSignatureResultArrayType2 { func foo() -> Int[0 { // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} return [0] // expected-error {{cannot convert return expression of type '[Int]' to return type 'Int'}} } } struct ErrorInFunctionSignatureResultArrayType3 { func foo() -> Int[0] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType4 { func foo() -> Int[0_1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType5 { func foo() -> Int[0b1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType11 { // expected-note{{in declaration of 'ErrorInFunctionSignatureResultArrayType11'}} func foo() -> Int[(a){a++}] { // expected-error {{consecutive declarations on a line must be separated by ';'}} {{29-29=;}} expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} expected-error {{use of unresolved identifier 'a'}} expected-error {{expected declaration}} } } //===--- Recovery for missing initial value in var decls. struct MissingInitializer1 { var v1 : Int = // expected-error {{expected initial value after '='}} } //===--- Recovery for expr-postfix. func exprPostfix1(x : Int) { x. // expected-error {{expected member name following '.'}} } func exprPostfix2() { _ = .42 // expected-error {{'.42' is not a valid floating point literal; it must be written '0.42'}} {{7-7=0}} } //===--- Recovery for expr-super. class Base {} class ExprSuper1 { init() { super // expected-error {{expected '.' or '[' after 'super'}} } } class ExprSuper2 { init() { super. // expected-error {{expected member name following '.'}} } } //===--- Recovery for braces inside a nominal decl. struct BracesInsideNominalDecl1 { // expected-note{{in declaration of 'BracesInsideNominalDecl1'}} { // expected-error {{expected declaration}} aaa } typealias A = Int } func use_BracesInsideNominalDecl1() { // Ensure that the typealias decl is not skipped. var _ : BracesInsideNominalDecl1.A // no-error } class SR771 { // expected-note {{in declaration of 'SR771'}} print("No one else was in the room where it happened") // expected-error {{expected declaration}} } extension SR771 { // expected-note {{in extension of 'SR771'}} print("The room where it happened, the room where it happened") // expected-error {{expected declaration}} } //===--- Recovery for wrong decl introducer keyword. class WrongDeclIntroducerKeyword1 { // expected-note{{in declaration of 'WrongDeclIntroducerKeyword1'}} notAKeyword() {} // expected-error {{expected declaration}} func foo() {} class func bar() {} } // <rdar://problem/18502220> [swift-crashes 078] parser crash on invalid cast in sequence expr Base=1 as Base=1 // expected-error {{cannot assign to immutable expression of type 'Base'}} // <rdar://problem/18634543> Parser hangs at swift::Parser::parseType public enum TestA { // expected-error @+1{{expected '{' in body of function declaration}} public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}} // expected-error@+1{{expected parameter name followed by ':'}} s._core.count != 0, "Can't form a Character from an empty String") } public enum TestB { // expected-error@+1{{expected '{' in body of function declaration}} public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}} // expected-error@+1 {{expected parameter name followed by ':'}} s._core.count ?= 0, "Can't form a Character from an empty String") } // <rdar://problem/18634543> Infinite loop and unbounded memory consumption in parser class bar {} var baz: bar // expected-error@+1{{unnamed parameters must be written with the empty name '_'}} func foo1(bar!=baz) {} // expected-note {{did you mean 'foo1'?}} // expected-error@+1{{unnamed parameters must be written with the empty name '_'}} func foo2(bar! = baz) {}// expected-note {{did you mean 'foo2'?}} // rdar://19605567 // expected-error@+1{{use of unresolved identifier 'esp'}} switch esp { case let (jeb): // expected-error@+5{{operator with postfix spacing cannot start a subexpression}} // expected-error@+4{{consecutive statements on a line must be separated by ';'}} {{15-15=;}} // expected-error@+3{{'>' is not a prefix unary operator}} // expected-error@+2{{expected an identifier to name generic parameter}} // expected-error@+1{{expected '{' in class}} class Ceac<}> {} // expected-error@+1{{extraneous '}' at top level}} {{1-2=}} } #if true // rdar://19605164 // expected-error@+2{{use of undeclared type 'S'}} struct Foo19605164 { func a(s: S[{{g) -> Int {} // expected-error@+2 {{expected parameter name followed by ':'}} // expected-error@+1 {{expected ',' separator}} }}} #endif // rdar://19605567 // expected-error@+3{{expected '(' for initializer parameters}} // expected-error@+2{{initializers may only be declared within a type}} // expected-error@+1{{expected an identifier to name generic parameter}} func F() { init<( } )} // expected-note {{did you mean 'F'?}} struct InitializerWithName { init x() {} // expected-error {{initializers cannot have a name}} {{8-9=}} } struct InitializerWithNameAndParam { init a(b: Int) {} // expected-error {{initializers cannot have a name}} {{8-9=}} } struct InitializerWithLabels { init c d: Int {} // expected-error @-1 {{expected '(' for initializer parameters}} // expected-error @-2 {{expected declaration}} // expected-error @-3 {{consecutive declarations on a line must be separated by ';'}} // expected-note @-5 {{in declaration of 'InitializerWithLabels'}} } // rdar://20337695 func f1() { // expected-error @+6 {{use of unresolved identifier 'C'}} // expected-note @+5 {{did you mean 'n'?}} // expected-error @+4 {{unary operator cannot be separated from its operand}} {{11-12=}} // expected-error @+3 {{'==' is not a prefix unary operator}} // expected-error @+2 {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error@+1 {{type annotation missing in pattern}} let n == C { get {} // expected-error {{use of unresolved identifier 'get'}} } } // <rdar://problem/20489838> QoI: Nonsensical error and fixit if "let" is missing between 'if let ... where' clauses func testMultiPatternConditionRecovery(x: Int?) { // expected-error@+1 {{expected ',' joining parts of a multi-clause condition}} {{15-21=,}} if let y = x where y == 0, let z = x { _ = y _ = z } if var y = x, y == 0, var z = x { z = y; y = z } if var y = x, z = x { // expected-error {{expected 'var' in conditional}} {{17-17=var }} z = y; y = z } // <rdar://problem/20883210> QoI: Following a "let" condition with boolean condition spouts nonsensical errors guard let x: Int? = 1, x == 1 else { } // expected-warning @-1 {{explicitly specified type 'Int?' adds an additional level of optional to the initializer, making the optional check always succeed}} {{16-20=Int}} } // rdar://20866942 func testRefutableLet() { var e : Int? let x? = e // expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error @-1 {{expected expression}} // expected-error @-2 {{type annotation missing in pattern}} } // <rdar://problem/19833424> QoI: Bad error message when using Objective-C literals (@"Hello") in Swift files let myString = @"foo" // expected-error {{string literals in Swift are not preceded by an '@' sign}} {{16-17=}} // <rdar://problem/16990885> support curly quotes for string literals // expected-error @+1 {{unicode curly quote found, replace with '"'}} {{35-38="}} let curlyQuotes1 = “hello world!” // expected-error {{unicode curly quote found, replace with '"'}} {{20-23="}} // expected-error @+1 {{unicode curly quote found, replace with '"'}} {{20-23="}} let curlyQuotes2 = “hello world!" // <rdar://problem/21196171> compiler should recover better from "unicode Specials" characters let tryx = 123 // expected-error 2 {{invalid character in source file}} {{5-8= }} // <rdar://problem/21369926> Malformed Swift Enums crash playground service enum Rank: Int { // expected-error {{'Rank' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} case Ace = 1 case Two = 2.1 // expected-error {{cannot convert value of type 'Double' to raw type 'Int'}} } // rdar://22240342 - Crash in diagRecursivePropertyAccess class r22240342 { lazy var xx: Int = { foo { // expected-error {{use of unresolved identifier 'foo'}} let issueView = 42 issueView.delegate = 12 } return 42 }() } // <rdar://problem/22387625> QoI: Common errors: 'let x= 5' and 'let x =5' could use Fix-its func r22387625() { let _= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{8-8= }} let _ =5 // expected-error{{'=' must have consistent whitespace on both sides}} {{10-10= }} } // <https://bugs.swift.org/browse/SR-3135> func SR3135() { let _: Int= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{13-13= }} let _: Array<Int>= [] // expected-error{{'=' must have consistent whitespace on both sides}} {{20-20= }} } // <rdar://problem/23086402> Swift compiler crash in CSDiag protocol A23086402 { var b: B23086402 { get } } protocol B23086402 { var c: [String] { get } } func test23086402(a: A23086402) { print(a.b.c + "") // should not crash but: expected-error {{}} } // <rdar://problem/23550816> QoI: Poor diagnostic in argument list of "print" (varargs related) // The situation has changed. String now conforms to the RangeReplaceableCollection protocol // and `ss + s` becomes ambiguous. Diambiguation is provided with the unavailable overload // in order to produce a meaningful diagnostics. (Related: <rdar://problem/31763930>) func test23550816(ss: [String], s: String) { print(ss + s) // expected-error {{'+' is unavailable: Operator '+' cannot be used to append a String to a sequence of strings}} } // <rdar://problem/23719432> [practicalswift] Compiler crashes on &(Int:_) func test23719432() { var x = 42 &(Int:x) // expected-error {{expression type 'inout _' is ambiguous without more context}} } // <rdar://problem/19911096> QoI: terrible recovery when using '·' for an operator infix operator · { // expected-error {{'·' is considered to be an identifier, not an operator}} associativity none precedence 150 } // <rdar://problem/21712891> Swift Compiler bug: String subscripts with range should require closing bracket. func r21712891(s : String) -> String { let a = s.startIndex..<s.startIndex _ = a // The specific errors produced don't actually matter, but we need to reject this. return "\(s[a)" // expected-error {{expected ']' in expression list}} expected-note {{to match this opening '['}} } // <rdar://problem/24029542> "Postfix '.' is reserved" error message" isn't helpful func postfixDot(a : String) { _ = a.utf8 _ = a. utf8 // expected-error {{extraneous whitespace after '.' is not permitted}} {{9-12=}} _ = a. // expected-error {{expected member name following '.'}} a. // expected-error {{expected member name following '.'}} } // <rdar://problem/22290244> QoI: "UIColor." gives two issues, should only give one func f() { _ = ClassWithStaticDecls. // expected-error {{expected member name following '.'}} }
apache-2.0
adrfer/swift
validation-test/compiler_crashers_fixed/26607-swift-parser-parsedecl.swift
13
251
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let A{struct Q{>init{class case, > >
apache-2.0
avito-tech/Paparazzo
Paparazzo/Core/VIPER/ImageCropping/View/RotationSliderView.swift
1
5344
import UIKit final class RotationSliderView: UIView, UIScrollViewDelegate { // MARK: - Subviews private let scrollView = UIScrollView() private let scaleView = SliderScaleView() private let thumbView = UIView() private let alphaMaskLayer = CAGradientLayer() // MARK: - Properties private var minimumValue: Float = 0 private var maximumValue: Float = 1 private var currentValue: Float = 0 // MARK: - UIView override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear contentMode = .redraw scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.bounces = false scrollView.delegate = self thumbView.backgroundColor = .black thumbView.layer.cornerRadius = scaleView.divisionWidth / 2 alphaMaskLayer.startPoint = CGPoint(x: 0, y: 0) alphaMaskLayer.endPoint = CGPoint(x: 1, y: 0) alphaMaskLayer.locations = [0, 0.2, 0.8, 1] alphaMaskLayer.colors = [ UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor ] layer.mask = alphaMaskLayer scrollView.addSubview(scaleView) addSubview(scrollView) addSubview(thumbView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // Высчитываем этот inset, чтобы в случаях, когда слайдер находится в крайних положениях, // метки на шкале и указатель текущего значения совпадали let sideInset = ((bounds.size.width - scaleView.divisionWidth) / 2).truncatingRemainder(dividingBy: scaleView.divisionWidth + scaleView.divisionsSpacing) scaleView.contentInsets = UIEdgeInsets(top: 0, left: sideInset, bottom: 0, right: sideInset) scaleView.frame = CGRect(origin: .zero, size: scaleView.sizeThatFits(bounds.size)) scrollView.frame = bounds scrollView.contentSize = scaleView.frame.size thumbView.size = CGSize(width: scaleView.divisionWidth, height: scaleView.height) thumbView.center = bounds.center alphaMaskLayer.frame = bounds adjustScrollViewOffset() } // MARK: - RotationSliderView var onSliderValueChange: ((Float) -> ())? func setMiminumValue(_ value: Float) { minimumValue = value } func setMaximumValue(_ value: Float) { maximumValue = value } func setValue(_ value: Float) { currentValue = max(minimumValue, min(maximumValue, value)) adjustScrollViewOffset() } // MARK: - UIScrollViewDelegate func scrollViewDidScroll(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset.x let significantWidth = scrollView.contentSize.width - bounds.size.width let percentage = offset / significantWidth let value = minimumValue + (maximumValue - minimumValue) * Float(percentage) onSliderValueChange?(value) } // Это отключает deceleration у scroll view func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { scrollView.setContentOffset(scrollView.contentOffset, animated: true) } // MARK: - Private private func adjustScrollViewOffset() { let percentage = (currentValue - minimumValue) / (maximumValue - minimumValue) scrollView.contentOffset = CGPoint( x: CGFloat(percentage) * (scrollView.contentSize.width - bounds.size.width), y: 0 ) } } private final class SliderScaleView: UIView { var contentInsets = UIEdgeInsets.zero let divisionsSpacing = CGFloat(14) let divisionsCount = 51 let divisionWidth = CGFloat(2) override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func sizeThatFits(_ size: CGSize) -> CGSize { var width = CGFloat(divisionsCount) * divisionWidth width += CGFloat(divisionsCount - 1) * divisionsSpacing width += contentInsets.left + contentInsets.right return CGSize(width: width, height: size.height) } override func draw(_ rect: CGRect) { super.draw(rect) for i in 0 ..< divisionsCount { let rect = CGRect( x: bounds.left + contentInsets.left + CGFloat(i) * (divisionWidth + divisionsSpacing), y: bounds.top, width: divisionWidth, height: bounds.size.height ) UIColor.RGBS(rgb: 217).setFill() UIBezierPath(roundedRect: rect, cornerRadius: divisionWidth / 2).fill() } } }
mit
Staance/Swell
Swell/Swell.swift
1
18621
// // Swell.swift // Swell // // Created by Hubert Rabago on 6/26/14. // Copyright (c) 2014 Minute Apps LLC. All rights reserved. // import Foundation struct LoggerConfiguration { var name: String var level: LogLevel? var formatter: LogFormatter? var locations: [LogLocation] init(name: String) { self.name = name self.locations = [LogLocation]() } func description() -> String { var locationsDesc = "" for loc in locations { locationsDesc += loc.description() } return "\(name) \(level?.desciption()) \(formatter?.description()) \(locationsDesc)" } } // We declare this here because there isn't any support yet for class var / class let let globalSwell = Swell(); public class Swell { lazy var swellLogger: Logger = { let result = getLogger("Shared") return result }() var selector = LogSelector() var allLoggers = Dictionary<String, Logger>() var rootConfiguration = LoggerConfiguration(name: "ROOT") var sharedConfiguration = LoggerConfiguration(name: "Shared") var allConfigurations = Dictionary<String, LoggerConfiguration>() var enabled = true; init() { // This configuration is used by the shared logger sharedConfiguration.formatter = QuickFormatter(format: .LevelMessage) sharedConfiguration.level = LogLevel.TRACE sharedConfiguration.locations += [ConsoleLocation.getInstance()] // The root configuration is where all other configurations are based off of rootConfiguration.formatter = QuickFormatter(format: .LevelNameMessage) rootConfiguration.level = LogLevel.TRACE rootConfiguration.locations += [ConsoleLocation.getInstance()] readConfigurationFile() } //======================================================================================== // Global/convenience log methods used for quick logging public class func trace<T>(@autoclosure message: () -> T) { globalSwell.swellLogger.trace(message) } public class func debug<T>(@autoclosure message: () -> T) { globalSwell.swellLogger.debug(message) } public class func info<T>(@autoclosure message: () -> T) { globalSwell.swellLogger.info(message) } public class func warn<T>(@autoclosure message: () -> T) { globalSwell.swellLogger.warn(message) } public class func error<T>(@autoclosure message: () -> T) { globalSwell.swellLogger.error(message) } public class func severe<T>(@autoclosure message: () -> T) { globalSwell.swellLogger.severe(message) } public class func trace(fn: () -> String) { globalSwell.swellLogger.trace(fn()) } public class func debug(fn: () -> String) { globalSwell.swellLogger.debug(fn()) } public class func info(fn: () -> String) { globalSwell.swellLogger.info(fn()) } public class func warn(fn: () -> String) { globalSwell.swellLogger.warn(fn()) } public class func error(fn: () -> String) { globalSwell.swellLogger.error(fn()) } public class func severe(fn: () -> String) { globalSwell.swellLogger.severe(fn()) } //==================================================================================================== // Public methods /// Returns the logger configured for the given name. /// This is the recommended way of retrieving a Swell logger. public class func getLogger(name: String) -> Logger { return globalSwell.getLogger(name); } /// Turns off all logging. public class func disableLogging() { globalSwell.disableLogging() } //==================================================================================================== // Internal methods serving the public methods func disableLogging() { enabled = false for (_, value) in allLoggers { value.enabled = false } } func enableLogging() { enabled = true for (_, value) in allLoggers { value.enabled = selector.shouldEnable(value) } } // Register the given logger. This method should be called // for ALL loggers created. This facilitates enabling/disabling of // loggers based on user configuration. class func registerLogger(logger: Logger) { globalSwell.registerLogger(logger); } func registerLogger(logger: Logger) { allLoggers[logger.name] = logger; evaluateLoggerEnabled(logger); } func evaluateLoggerEnabled(logger: Logger) { logger.enabled = self.enabled && selector.shouldEnable(logger); } /// Returns the Logger instance configured for a given logger name. /// Use this to get Logger instances for use in classes. func getLogger(name: String) -> Logger { let logger = allLoggers[name] if (logger != nil) { return logger! } else { let result: Logger = createLogger(name) allLoggers[name] = result return result } } /// Creates a new Logger instance based on configuration returned by getConfigurationForLoggerName() /// This is intended to be in an internal method and should not be called by other classes. /// Use getLogger(name) to get a logger for normal use. func createLogger(name: String) -> Logger { let config = getConfigurationForLoggerName(name) let result = Logger(name: name, level: config.level!, formatter: config.formatter!, logLocation: config.locations[0]) // Now we need to handle potentially > 1 locations if config.locations.count > 1 { for (index,location) in config.locations.enumerate() { if (index > 0) { result.locations += [location] } } } return result } //==================================================================================================== // Methods for managing the configurations from the plist file /// Returns the current configuration for a given logger name based on Swell.plist /// and the root configuration. func getConfigurationForLoggerName(name: String) -> LoggerConfiguration { var config: LoggerConfiguration = LoggerConfiguration(name: name); // first, populate it with values from the root config config.formatter = rootConfiguration.formatter config.level = rootConfiguration.level config.locations += rootConfiguration.locations if (name == "Shared") { if let level = sharedConfiguration.level { config.level = level } if let formatter = sharedConfiguration.formatter { config.formatter = formatter } if sharedConfiguration.locations.count > 0 { config.locations = sharedConfiguration.locations } } // Now see if there's a config specifically for this logger // In later versions, we can consider tree structures similar to Log4j // For now, let's require an exact match for the name let keys = allConfigurations.keys for key in keys { // Look for the entry with the same name if (key == name) { let temp = allConfigurations[key] if let spec = temp { if let formatter = spec.formatter { config.formatter = formatter } if let level = spec.level { config.level = level } if spec.locations.count > 0 { config.locations = spec.locations } } } } return config; } //==================================================================================================== // Methods for reading the Swell.plist file func readConfigurationFile() { let filename: String? = NSBundle.mainBundle().pathForResource("Swell", ofType: "plist"); var dict: NSDictionary? = nil; if let bundleFilename = filename { dict = NSDictionary(contentsOfFile: bundleFilename) } if let map: Dictionary<String, AnyObject> = dict as? Dictionary<String, AnyObject> { //----------------------------------------------------------------- // Read the root configuration let configuration = readLoggerPList("ROOT", map: map); //Swell.info("map: \(map)"); // Now any values configured, we put in our root configuration if let formatter = configuration.formatter { rootConfiguration.formatter = formatter } if let level = configuration.level { rootConfiguration.level = level } if configuration.locations.count > 0 { rootConfiguration.locations = configuration.locations } //----------------------------------------------------------------- // Now look for any keys that don't start with SWL, and if it contains a dictionary value, let's read it let keys = map.keys for key in keys { if (!key.hasPrefix("SWL")) { let value: AnyObject? = map[key] if let submap: Dictionary<String, AnyObject> = value as? Dictionary<String, AnyObject> { let subconfig = readLoggerPList(key, map: submap) applyLoggerConfiguration(key, configuration: subconfig) } } } //----------------------------------------------------------------- // Now check if there is an enabled/disabled rule specified var item: AnyObject? = nil // Set the LogLevel item = map["SWLEnable"] if let value: AnyObject = item { if let rule: String = value as? String { selector.enableRule = rule } } item = map["SWLDisable"] if let value: AnyObject = item { if let rule: String = value as? String { selector.disableRule = rule } } } } /// Specifies or modifies the configuration of a logger. /// If any aspect of the configuration was not provided, and there is a pre-existing value for it, /// the pre-existing value will be used for it. /// For example, if two consecutive calls were made: /// configureLogger("MyClass", level: LogLevel.DEBUG, formatter: MyCustomFormatter()) /// configureLogger("MyClass", level: LogLevel.INFO, location: ConsoleLocation()) /// then the resulting configuration for MyClass would have MyCustomFormatter, ConsoleLocation, and LogLevel.INFO. func configureLogger(loggerName: String, level givenLevel: LogLevel? = nil, formatter givenFormatter: LogFormatter? = nil, location givenLocation: LogLocation? = nil) { var oldConfiguration: LoggerConfiguration? if allConfigurations.indexForKey(loggerName) != nil { oldConfiguration = allConfigurations[loggerName] } var newConfiguration = LoggerConfiguration(name: loggerName) if let level = givenLevel { newConfiguration.level = level } else if let level = oldConfiguration?.level { newConfiguration.level = level } if let formatter = givenFormatter { newConfiguration.formatter = formatter } else if let formatter = oldConfiguration?.formatter { newConfiguration.formatter = formatter } if let location = givenLocation { newConfiguration.locations += [location] } else if oldConfiguration?.locations.count > 0 { newConfiguration.locations = oldConfiguration!.locations } applyLoggerConfiguration(loggerName, configuration: newConfiguration) } /// Store the configuration given for the specified logger. /// If the logger already exists, update its configuration to reflect what's in the logger. func applyLoggerConfiguration(loggerName: String, configuration: LoggerConfiguration) { // Record this custom config in our map allConfigurations[loggerName] = configuration // See if the logger with the given name already exists. // If so, update the configuration it's using. if let logger = allLoggers[loggerName] { // TODO - There should be a way to keep calls to logger.log while this is executing if let level = configuration.level { logger.level = level } if let formatter = configuration.formatter { logger.formatter = formatter } if configuration.locations.count > 0 { logger.locations.removeAll(keepCapacity: false) logger.locations += configuration.locations } } } func readLoggerPList(loggerName: String, map: Dictionary<String, AnyObject>) -> LoggerConfiguration { var configuration = LoggerConfiguration(name: loggerName) var item: AnyObject? = nil // Set the LogLevel item = map["SWLLevel"] if let value: AnyObject = item { if let level: String = value as? String { configuration.level = LogLevel.getLevel(level) } } // Set the formatter; First, look for a QuickFormat spec item = map["SWLQuickFormat"] if let value: AnyObject = item { configuration.formatter = getConfiguredQuickFormatter(configuration, item: value); } else { // If no QuickFormat was given, look for a FlexFormat spec item = map["SWLFlexFormat"] if let value: AnyObject = item { configuration.formatter = getConfiguredFlexFormatter(configuration, item: value); } else { let formatKey = getFormatKey(map) print("formatKey=\(formatKey)") } } // Set the location for the logs item = map["SWLLocation"] if let value: AnyObject = item { configuration.locations = getConfiguredLocations(configuration, item: value, map: map); } return configuration } func getConfiguredQuickFormatter(configuration: LoggerConfiguration, item: AnyObject) -> LogFormatter? { if let formatString: String = item as? String { let formatter = QuickFormatter.logFormatterForString(formatString) return formatter } return nil } func getConfiguredFlexFormatter(configuration: LoggerConfiguration, item: AnyObject) -> LogFormatter? { if let formatString: String = item as? String { let formatter = FlexFormatter.logFormatterForString(formatString); return formatter } return nil } func getConfiguredFileLocation(configuration: LoggerConfiguration, item: AnyObject) -> LogLocation? { if let filename: String = item as? String { let logLocation = FileLocation.getInstance(filename); return logLocation } return nil } func getConfiguredLocations(configuration: LoggerConfiguration, item: AnyObject, map: Dictionary<String, AnyObject>) -> [LogLocation] { var results = [LogLocation]() if let configuredValue: String = item as? String { // configuredValue is the raw value in the plist // values is the array from configuredValue let values = configuredValue.lowercaseString.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) for value in values { if (value == "file") { // handle file name let filenameValue: AnyObject? = map["SWLLocationFilename"] if let filename: AnyObject = filenameValue { let fileLocation = getConfiguredFileLocation(configuration, item: filename); if fileLocation != nil { results += [fileLocation!] } } } else if (value == "console") { results += [ConsoleLocation.getInstance()] } else { print("Unrecognized location value in Swell.plist: '\(value)'") } } } return results } func getFormatKey(map: Dictionary<String, AnyObject>) -> String? { for (key, _) in map { if ((key.hasPrefix("SWL")) && (key.hasSuffix("Format"))) { let start = key.startIndex.advancedBy(3) let end = key.startIndex.advancedBy(-6) let result: String = key[start..<end] return result } } return nil; } func getFunctionFormat(function: String) -> String { var result = function; if (result.hasPrefix("Optional(")) { let len = "Optional(".characters.count let start = result.startIndex.advancedBy(len) let end = result.endIndex.advancedBy(-len) let range = start..<end result = result[range] } if (!result.hasSuffix(")")) { result = result + "()" } return result } }
apache-2.0
siggb/MarvelUniverse
marvel-universe/Tests/UITests/UITests.swift
1
1213
// // UITests.swift // UITests // // Created by sig on 07/11/2016. // Copyright © 2016 Sibagatov Ildar. All rights reserved. // import XCTest class UITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { let app = XCUIApplication() app.tables.staticTexts["A-Bomb (HAS)"].tap() app.buttons["arrowBack"].tap() } }
mit
sweepforswift/sweep
Sweep/AttributedStrings.swift
1
4803
// // AttributedStrings.swift // Sweep // // Created by Will Mock on 2/24/17. // Copyright © 2017 Michael Smith Jr. All rights reserved. // import Foundation public enum Style{ case bold case italic } public extension NSMutableAttributedString { /** Changes the font type of the NSMutableAttributedString to the font matching the parameter - parameter fontName: Takes in the name of the font that is desired - returns: an NSMutableAttributedString with the font applied */ public func changeFontType(fontName: String)->NSMutableAttributedString{ let fonts: [String] = UIFont.familyNames let myAttribute = [ NSFontAttributeName: UIFont.fontNames(forFamilyName: fontName) ] if fonts.contains(fontName) { print("success") self.addAttribute(self.string, value: myAttribute, range: NSMakeRange(0, self.length)) }else{ print("failed to change font") } return self } /** Changes the font color of the NSMutableAttributedString to the color matching the parameter color. This function also has the option to select only a subset of the original NSMutableAttributedString to change the font color of. - parameter fontName: Takes in the String name of the font that is desired - parameter range: Takes in an NSRange? object that specifies the range on which the color will be applied. This will apply to the entire NSMutableAttributedString if no NSrange? is specified - returns: an NSMutableAttributedString with the font color applied */ public func changeFontColor(color: UIColor, range: NSRange? = nil)->NSMutableAttributedString{ let attributedString = NSMutableAttributedString(string: self.string) var trueRange: NSRange if let range = range{ trueRange = range }else{ trueRange = (self.string as NSString).range(of: self.string) } attributedString.addAttribute(NSForegroundColorAttributeName, value: color , range: trueRange) return attributedString } /** Changes the NSBackgroundColorAttributeName of the NSMutableAttributedString to the color yellow (i.e highlighting). This function has the optionional parameter called range that takes in an NSRange? to select only a subset of the original NSMutableAttributedString to highlight. - parameter range: Takes in an NSRange? object that specifies the range on which the highlighting will be applied. This will apply to the entire NSMutableAttributedString if no NSrange? is specified - returns: an NSMutableAttributedString with the highlighting applied */ public func highlight(range: NSRange? = nil)->NSMutableAttributedString{ let attributedString = NSMutableAttributedString(string: self.string) var trueRange: NSRange if let range = range{ trueRange = range }else{ trueRange = (self.string as NSString).range(of: self.string) } attributedString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellow , range: trueRange) return attributedString } /** Adding a constraint of bold or italic to an NSMutableAttributedString based on the style parameter. This function also takes in an Int for size and an optional NSRange? to change a subset of the original NSMutableAttributedString. - parameter style: enum of type Style - parameter fontSize: Int that specifies the desired system size of the font - parameter range: Takes in an NSRange? object that specifies the range on which the color will be applied. This will apply to the entire NSMutableAttributedString if no NSrange? is specified - returns: an NSMutableAttributedString with the font style applied */ public func addConstraints(style: Style, fontSize: Int = 17, range: NSRange? = nil)->NSMutableAttributedString{ var trueRange: NSRange if let range = range{ trueRange = range }else{ trueRange = NSMakeRange(0, self.length) } switch style { case .bold: let myAttribute = [ NSFontAttributeName: UIFont.boldSystemFont(ofSize: CGFloat(fontSize)) ] self.addAttribute(self.string, value: myAttribute, range: trueRange) case .italic: let myAttribute = [ NSFontAttributeName: UIFont.italicSystemFont(ofSize: CGFloat(fontSize)) ] self.addAttribute(self.string, value: myAttribute, range: trueRange) } return self } }
mit
SFantasy/swift-tour
Protocols&&Extensions.playground/section-1.swift
1
1420
// Experiments in Swift Programming Language // // Protocols and Extensions // protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() { simpleDescription += " Now 100% adjusted." } } var a = SimpleClass() a.adjust() let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += " (adjusted)" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription // Write an enumeration that conforms the protocol enum SimpleEnum: ExampleProtocol { case a, b var simpleDescription: String{ get { return self.getDescription() } } func getDescription() -> String { switch self { case .a: return "it is a" case .b: return "it is b" } } mutating func adjust() { self = SimpleEnum.b } } var c = SimpleEnum.a c.simpleDescription c.adjust() c.simpleDescription // Write an extension for Double type that adds an absoluteValue property. extension Double { var absoluteValue: Double { return abs(self) } } 7.3.absoluteValue (-7.0).absoluteValue
mit
jdarowski/RGSnackBar
RGSnackBar/Classes/RGMessageSnackBarAnimation.swift
1
3749
// // RGMessageSnackBarAnimation.swift // RGSnackBar // // Created by Jakub Darowski on 04/09/2017. // // import UIKit import Stevia public typealias RGSnackBarAnimationBlock = ((RGMessageSnackBarView, UIView, Bool) -> Void) /** * This is where the fun begins. Instantiate (or extend)this class to define * your very own buttery smooth, candy-like animations for the snackbar. */ open class RGMessageSnackBarAnimation: NSObject { /// The block that will be executed before animating open var preAnimationBlock: RGSnackBarAnimationBlock? /// The animation block - will be executed inside UIView.animate(...) open var animationBlock: RGSnackBarAnimationBlock /// The block that will be executed in the completion block of animate(...) open var postAnimationBlock: RGSnackBarAnimationBlock? /// The duration of the animation open var animationDuration: TimeInterval /// States whether the snackbar is off-screen open var beginsOffscreen: Bool /** * The only constructor you'll need. * * - Parameter preBlock: duh * - Parameter animationBlock: double duh * - Parameter postBlock: duh * - Parameter animationDuration: the duration of just the animation itself. * - Parameter beginsOffscreen: whether the snackbar starts offscreen */ public init(preBlock: RGSnackBarAnimationBlock?, animationBlock: @escaping RGSnackBarAnimationBlock, postBlock: RGSnackBarAnimationBlock?, animationDuration: TimeInterval=0.4, beginsOffscreen: Bool=false) { self.preAnimationBlock = preBlock self.animationBlock = animationBlock self.postAnimationBlock = postBlock self.animationDuration = animationDuration self.beginsOffscreen = beginsOffscreen super.init() } /// A predefined zoom-in animation, UIAlertView style public static let zoomIn: RGMessageSnackBarAnimation = RGMessageSnackBarAnimation(preBlock: { (snackBarView, _, isPresenting) in if isPresenting { snackBarView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) } }, animationBlock: { (snackBarView, parentView, isPresenting) in if isPresenting { snackBarView.alpha = 1.0 snackBarView.transform = CGAffineTransform.identity } else { snackBarView.alpha = 0.0 snackBarView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) } }, postBlock: nil, animationDuration: 0.2, beginsOffscreen: false) /// A predefined slide up animation, system banner style (just opposite) public static let slideUp: RGMessageSnackBarAnimation = RGMessageSnackBarAnimation(preBlock: { (snackBarView, parentView, isPresenting) in if isPresenting { let height = snackBarView.frame.size.height snackBarView.bottomConstraint?.constant = height + snackBarView.bottomMargin snackBarView.alpha = 1.0 parentView.layoutIfNeeded() snackBarView.bottomConstraint?.constant = -(snackBarView.bottomMargin) } else { snackBarView.bottomConstraint?.constant = snackBarView.frame.size.height } }, animationBlock: { (snackBarView, parentView, isPresenting) in parentView.layoutIfNeeded() }, postBlock: { (snackBarView, parentView, isPresenting) in if !isPresenting { snackBarView.alpha = 0.0 } }, animationDuration: 0.2, beginsOffscreen: true) }
mit
tomtclai/swift-algorithm-club
Brute-Force String Search/BruteForceStringSearch.swift
9
532
/* Brute-force string search */ extension String { func indexOf(_ pattern: String) -> String.Index? { for i in self.characters.indices { var j = i var found = true for p in pattern.characters.indices { if j == self.characters.endIndex || self[j] != pattern[p] { found = false break } else { j = self.characters.index(after: j) } } if found { return i } } return nil } }
mit
tkremenek/swift
validation-test/compiler_crashers_fixed/26743-swift-typechecker-checkinheritanceclause.swift
65
463
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func d{struct B<T{ class d class c:d{ struct B{struct B{func d<B
apache-2.0
TouchInstinct/LeadKit
TISwiftUtils/Sources/Helpers/Typealias.swift
1
3472
// // Copyright (c) 2020 Touch Instinct // // 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. // /// Closure with custom arguments and return value. public typealias Closure<Input, Output> = (Input) -> Output /// Closure with no arguments and custom return value. public typealias ResultClosure<Output> = () -> Output /// Closure that takes custom arguments and returns Void. public typealias ParameterClosure<Input> = Closure<Input, Void> // MARK: Throwable versions /// Closure with custom arguments and return value, may throw an error. public typealias ThrowableClosure<Input, Output> = (Input) throws -> Output /// Closure with no arguments and custom return value, may throw an error. public typealias ThrowableResultClosure<Output> = () throws -> Output /// Closure that takes custom arguments and returns Void, may throw an error. public typealias ThrowableParameterClosure<Input> = ThrowableClosure<Input, Void> // MARK: Concrete closures /// Closure that takes no arguments and returns Void. public typealias VoidClosure = ResultClosure<Void> /// Closure that takes no arguments, may throw an error and returns Void. public typealias ThrowableVoidClosure = () throws -> Void /// Async closure with custom arguments and return value. public typealias AsyncClosure<Input, Output> = (Input) async -> Output /// Async closure with no arguments and custom return value. public typealias AsyncResultClosure<Output> = () async -> Output /// Async closure that takes custom arguments and returns Void. public typealias AsyncParameterClosure<Input> = AsyncClosure<Input, Void> // MARK: Async throwable versions /// Async closure with custom arguments and return value, may throw an error. public typealias ThrowableAsyncClosure<Input, Output> = (Input) async throws -> Output /// Async closure with no arguments and custom return value, may throw an error. public typealias ThrowableAsyncResultClosure<Output> = () async throws -> Output /// Async closure that takes custom arguments and returns Void, may throw an error. public typealias ThrowableAsyncParameterClosure<Input> = ThrowableAsyncClosure<Input, Void> // MARK: Async concrete closures /// Async closure that takes no arguments and returns Void. public typealias AsyncVoidClosure = AsyncResultClosure<Void> /// Async closure that takes no arguments, may throw an error and returns Void. public typealias ThrowableAsyncVoidClosure = () async throws -> Void
apache-2.0
SiddharthChopra/KahunaSocialMedia
KahunaSocialMedia/Classes/Instagram/JsonClasses/IGDimension.swift
1
1013
// // IGDimension.swift // // Create by Kahuna on 13/11/2017 // Copyright © 2017. All rights reserved. // Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation class IGDimension: NSObject { var height: Int! var width: Int! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: NSDictionary) { height = dictionary["height"] as? Int width = dictionary["width"] as? Int } /** * Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> NSDictionary { let dictionary = NSMutableDictionary() if height != nil { dictionary["height"] = height } if width != nil { dictionary["width"] = width } return dictionary } }
mit
radex/swift-compiler-crashes
crashes-fuzzing/03202-swift-constraints-constraintsystem-finalize.swift
11
233
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func f<T{ if true{ enum B{ init(){ enum B{class A{func j var _=j
mit
radex/swift-compiler-crashes
crashes-fuzzing/23164-swift-parentype-get.swift
11
280
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension String{let:d{struct A{struct B{class a{struct Q{struct a{struct Q<T where g:a{struct Q<g where g:b.c
mit
CUBE-UA/UniversityPrograms-iOS
swift/UniversityPrograms/UniversityProgramsTests/UniversityProgramsTests.swift
1
1017
// // UniversityProgramsTests.swift // UniversityProgramsTests // // Created by greyson on 1/22/16. // Copyright © 2016 Greyson Wright. All rights reserved. // import XCTest @testable import UniversityPrograms class UniversityProgramsTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
bsd-3-clause
bugsnag/bugsnag-cocoa
features/fixtures/shared/scenarios/HandledErrorScenario.swift
1
472
// // Created by Jamie Lynch on 06/03/2018. // Copyright (c) 2018 Bugsnag. All rights reserved. // import Foundation /** * Sends a handled Error to Bugsnag */ class HandledErrorScenario: Scenario { override func startBugsnag() { self.config.autoTrackSessions = false; super.startBugsnag() } override func run() { let error = NSError(domain: "HandledErrorScenario", code: 100, userInfo: nil) Bugsnag.notifyError(error) } }
mit
NobodyNada/SwiftStack
Tests/SwiftStackTests/JsonHelperTests.swift
1
1396
// // JsonHelperTests.swift // SwiftStack // // Created by FelixSFD on 08.12.16. // // import XCTest import SwiftStack class JsonHelperTests: XCTestCase { func testEncoding() { let json = "{\"badge_counts\": {\"bronze\": 3,\"silver\": 2,\"gold\": 1},\"view_count\": 1000,\"down_vote_count\": 50,\"up_vote_count\": 90,\"answer_count\": 10,\"question_count\": 12,\"account_id\": 1,\"is_employee\": false,\"last_modified_date\": 1480858104,\"last_access_date\": 1480901304,\"age\": 40,\"reputation_change_year\": 9001,\"reputation_change_quarter\": 400,\"reputation_change_month\": 200,\"reputation_change_week\": 800,\"reputation_change_day\": 100,\"reputation\": 9001,\"creation_date\": 1480858104,\"user_type\": \"registered\",\"user_id\": 1,\"accept_rate\": 55,\"about_me\": \"about me block\",\"location\": \"An Imaginary World\",\"website_url\": \"http://example.com/\",\"link\": \"http://example.stackexchange.com/users/1/example-user\",\"profile_image\": \"https://www.gravatar.com/avatar/a007be5a61f6aa8f3e85ae2fc18dd66e?d=identicon&r=PG\",\"display_name\": \"Example User\"}" let user = User(jsonString: json) /*let encoded = JsonHelper.encode(object: user!) print(encoded) XCTAssertNotNil(encoded)*/ let jsonUser = user?.jsonString //print(jsonUser ?? "nil") XCTAssertNotNil(jsonUser) } }
mit
rellermeyer/99tsp
swift/gen/main.swift
1
7354
// // main.swift // pl // // Created by Michael Scaria on 11/28/16. // Copyright © 2016 michaelscaria. All rights reserved. // import Foundation struct City { var x = 0.0 var y = 0.0 init() { } init(x: Double, y: Double) { self.x = x self.y = y } func distance(from city: City) -> Double { let x_delta = x - city.x let y_delta = y - city.y return sqrt(pow(x_delta, 2) + pow(y_delta, 2)) } } extension City: Equatable { static func ==(lhs: City, rhs: City) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } } var allCities = [City]() struct Tour { var cities = [City]() { didSet { fitness = 0.0 distance = 0.0 } } var size: Int { get { return cities.count } } var fitness = 0.0 var distance = 0.0 init() { for _ in 0..<allCities.count { cities.append(City()) } } subscript(index: Int) -> City { get { return cities[index] } set { cities[index] = newValue } } func contains(city: City) -> Bool { return cities.contains(city) } mutating func getFitness() -> Double { if fitness == 0 { fitness = 1/getDistance() } return fitness } mutating func getDistance() -> Double { if distance == 0 { for (index, city) in cities.enumerated() { if index < cities.count - 1 { distance += city.distance(from: cities[index + 1]) } } } return distance } mutating func generateIndividual() { cities = allCities cities.sort { _,_ in arc4random_uniform(2) == 0 } } } struct Population { private var tours = [Tour]() var size: Int { get { return tours.count } } init(size: Int, initialize: Bool) { for _ in 0..<size { if initialize { var tour = Tour() tour.generateIndividual() tours.append(tour) } else { tours.append(Tour()) } } } subscript(index: Int) -> Tour { get { return tours[index] } set { tours[index] = newValue } } func getFittest() -> Tour { var fittest = tours.first! for i in 0..<tours.count { var tour = tours[i] if fittest.getFitness() < tour.getFitness() { fittest = tour } } return fittest } } let backgroundQueue: DispatchQueue! if #available(OSX 10.10, *) { backgroundQueue = DispatchQueue.global(qos: .background) } else { backgroundQueue = DispatchQueue.global(priority: .default) } let breedSemaphore = DispatchSemaphore(value: 0) var breedQueues = [DispatchQueue]() for i in 0..<5 { breedQueues.append(DispatchQueue(label: "Breed Queue \(i)")) } struct Genetic { let mutationRate = 0.015 let tournamentSize = 5 let elitism = true // this should only be called in one place to reduce race condition-related bugs func evolve(population: Population) -> Population { var newPop = Population(size: population.size, initialize: false) var offset = 0 if elitism { newPop[0] = population.getFittest() offset = 1 } // BREED let breedGroup = DispatchGroup() for i in offset..<population.size { breedQueues[i % breedQueues.count].async(group: breedGroup, execute: { let parent1 = self.select(from: population) let parent2 = self.select(from: population) let child = self.crossover(parent1: parent1, parent2: parent2) newPop[i] = child }) } breedGroup.notify(queue: DispatchQueue(label: "Breed Completion"), execute: { breedSemaphore.signal() }) breedSemaphore.wait() // MUTATE for i in offset..<population.size { newPop[i] = mutate(tour: newPop[i]) } return newPop } func crossover(parent1: Tour, parent2: Tour) -> Tour { var child = Tour() var start = Int(arc4random_uniform(UInt32(parent1.size))) var end = Int(arc4random_uniform(UInt32(parent1.size))) // make sure start is less than end if start > end { let oldEnd = end end = start start = oldEnd } var takenSlots = [Int]() if start < end { for i in (start+1)..<end { child[i] = parent1[i] takenSlots.append(i) } } // this part is very inefficent for i in 0..<allCities.count { if !child.contains(city: parent2[i]) { for j in 0..<allCities.count { if !takenSlots.contains(j) { child[j] = parent2[j] takenSlots.append(j) } } } } return child } func mutate(tour t: Tour) -> Tour { var tour = t for pos1 in 0..<tour.size { if Double(arc4random_uniform(1000))/1000.0 < mutationRate { let pos2 = Int(arc4random_uniform(UInt32(tour.size))) let city1 = tour[pos1] let city2 = tour[pos2] tour[pos2] = city1 tour[pos1] = city2 } } return tour } func select(from population: Population) -> Tour { var tournamentPop = Population(size: tournamentSize, initialize: false) for i in 0..<tournamentSize { let random = Int(arc4random_uniform(UInt32(population.size))) tournamentPop[i] = population[random] } return tournamentPop.getFittest() } } let programSemaphore = DispatchSemaphore(value: 0) func parse(file: [String]) { var i = 0 for line in file { if (i > 5) { let comps = line.components(separatedBy: " ").filter { return $0 != "" } if comps.count == 3 { let city = City(x: Double(comps[1])!, y: Double(comps[2])!) allCities.append(city) } } i += 1 } backgroundQueue.async { let genetic = Genetic() var pop = Population(size: allCities.count, initialize: true) var tour = pop.getFittest() print("Start: \(tour.getDistance())") for i in 0..<50 { pop = genetic.evolve(population: pop) if i % 1 == 0 { tour = pop.getFittest() print("\(i + 1). \(tour.getDistance())") } } tour = pop.getFittest() print("End: \(tour.getDistance())") programSemaphore.signal() } programSemaphore.wait() } let arguments = CommandLine.arguments if arguments.count > 1 { let file = arguments[1] do { let content = try String(contentsOfFile:file, encoding: String.Encoding.utf8) parse(file: content.components(separatedBy: "\n")) } catch _ as NSError {} }
bsd-3-clause
ytakzk/Swift-Alamofire-For-Qiita
swift-qiita/ViewController.swift
1
2808
// // ViewController.swift // swift-qiita // // Created by Yuta Akizuki on 2014/09/20. // Copyright (c) 2014年 ytakzk.me. All rights reserved. // import UIKit import Alamofire class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var articles: Array<Article>? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. articles = Array() // Get articles var result: NSArray? Alamofire.request(.GET, "https://qiita.com/api/v1/search?q=swift",parameters: nil, encoding: .JSON) .responseJSON { (request, response, JSON, error) in result = (JSON as NSArray) // Make models from Json data for (var i = 0; i < result?.count; i++) { let dic: NSDictionary = result![i] as NSDictionary var article: Article = Article( title: dic["title"] as String, userName: dic["user"]!["url_name"] as String, linkURL: dic["url"] as String, imageURL:dic["user"]!["profile_image_url"] as String ) self.articles?.append(article) } self.tableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return articles!.count } func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! { let cell: MyTableViewCell = tableView?.dequeueReusableCellWithIdentifier("Cell") as MyTableViewCell cell.article = articles?[indexPath.row] return cell; } func tableView(tableView: UITableView?, didSelectRowAtIndexPath indexPath:NSIndexPath!) { // When a cell has selected, open WebViewController. let cell: MyTableViewCell = tableView?.cellForRowAtIndexPath(indexPath) as MyTableViewCell self.performSegueWithIdentifier("WebViewController", sender: cell) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { super.prepareForSegue(segue, sender: sender) // Assign a model to WebViewController if segue.identifier == "WebViewController" { var cell : MyTableViewCell = sender as MyTableViewCell let vc: WebViewController = segue.destinationViewController as WebViewController vc.article = cell.article } } }
mit
apple/swift-nio
Tests/NIOPosixTests/EventLoopFutureTest+XCTest.swift
1
7250
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // EventLoopFutureTest+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension EventLoopFutureTest { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (EventLoopFutureTest) -> () throws -> Void)] { return [ ("testFutureFulfilledIfHasResult", testFutureFulfilledIfHasResult), ("testFutureFulfilledIfHasError", testFutureFulfilledIfHasError), ("testFoldWithMultipleEventLoops", testFoldWithMultipleEventLoops), ("testFoldWithSuccessAndAllSuccesses", testFoldWithSuccessAndAllSuccesses), ("testFoldWithSuccessAndOneFailure", testFoldWithSuccessAndOneFailure), ("testFoldWithSuccessAndEmptyFutureList", testFoldWithSuccessAndEmptyFutureList), ("testFoldWithFailureAndEmptyFutureList", testFoldWithFailureAndEmptyFutureList), ("testFoldWithFailureAndAllSuccesses", testFoldWithFailureAndAllSuccesses), ("testFoldWithFailureAndAllUnfulfilled", testFoldWithFailureAndAllUnfulfilled), ("testFoldWithFailureAndAllFailures", testFoldWithFailureAndAllFailures), ("testAndAllWithEmptyFutureList", testAndAllWithEmptyFutureList), ("testAndAllWithAllSuccesses", testAndAllWithAllSuccesses), ("testAndAllWithAllFailures", testAndAllWithAllFailures), ("testAndAllWithOneFailure", testAndAllWithOneFailure), ("testReduceWithAllSuccesses", testReduceWithAllSuccesses), ("testReduceWithOnlyInitialValue", testReduceWithOnlyInitialValue), ("testReduceWithAllFailures", testReduceWithAllFailures), ("testReduceWithOneFailure", testReduceWithOneFailure), ("testReduceWhichDoesFailFast", testReduceWhichDoesFailFast), ("testReduceIntoWithAllSuccesses", testReduceIntoWithAllSuccesses), ("testReduceIntoWithEmptyFutureList", testReduceIntoWithEmptyFutureList), ("testReduceIntoWithAllFailure", testReduceIntoWithAllFailure), ("testReduceIntoWithMultipleEventLoops", testReduceIntoWithMultipleEventLoops), ("testThenThrowingWhichDoesNotThrow", testThenThrowingWhichDoesNotThrow), ("testThenThrowingWhichDoesThrow", testThenThrowingWhichDoesThrow), ("testflatMapErrorThrowingWhichDoesNotThrow", testflatMapErrorThrowingWhichDoesNotThrow), ("testflatMapErrorThrowingWhichDoesThrow", testflatMapErrorThrowingWhichDoesThrow), ("testOrderOfFutureCompletion", testOrderOfFutureCompletion), ("testEventLoopHoppingInThen", testEventLoopHoppingInThen), ("testEventLoopHoppingInThenWithFailures", testEventLoopHoppingInThenWithFailures), ("testEventLoopHoppingAndAll", testEventLoopHoppingAndAll), ("testEventLoopHoppingAndAllWithFailures", testEventLoopHoppingAndAllWithFailures), ("testFutureInVariousScenarios", testFutureInVariousScenarios), ("testLoopHoppingHelperSuccess", testLoopHoppingHelperSuccess), ("testLoopHoppingHelperFailure", testLoopHoppingHelperFailure), ("testLoopHoppingHelperNoHopping", testLoopHoppingHelperNoHopping), ("testFlatMapResultHappyPath", testFlatMapResultHappyPath), ("testFlatMapResultFailurePath", testFlatMapResultFailurePath), ("testWhenAllSucceedFailsImmediately", testWhenAllSucceedFailsImmediately), ("testWhenAllSucceedResolvesAfterFutures", testWhenAllSucceedResolvesAfterFutures), ("testWhenAllSucceedIsIndependentOfFulfillmentOrder", testWhenAllSucceedIsIndependentOfFulfillmentOrder), ("testWhenAllCompleteResultsWithFailuresStillSucceed", testWhenAllCompleteResultsWithFailuresStillSucceed), ("testWhenAllCompleteResults", testWhenAllCompleteResults), ("testWhenAllCompleteResolvesAfterFutures", testWhenAllCompleteResolvesAfterFutures), ("testAlways", testAlways), ("testAlwaysWithFailingPromise", testAlwaysWithFailingPromise), ("testPromiseCompletedWithSuccessfulFuture", testPromiseCompletedWithSuccessfulFuture), ("testPromiseCompletedWithFailedFuture", testPromiseCompletedWithFailedFuture), ("testPromiseCompletedWithSuccessfulResult", testPromiseCompletedWithSuccessfulResult), ("testPromiseCompletedWithFailedResult", testPromiseCompletedWithFailedResult), ("testAndAllCompleteWithZeroFutures", testAndAllCompleteWithZeroFutures), ("testAndAllSucceedWithZeroFutures", testAndAllSucceedWithZeroFutures), ("testAndAllCompleteWithPreSucceededFutures", testAndAllCompleteWithPreSucceededFutures), ("testAndAllCompleteWithPreFailedFutures", testAndAllCompleteWithPreFailedFutures), ("testAndAllCompleteWithMixOfPreSuccededAndNotYetCompletedFutures", testAndAllCompleteWithMixOfPreSuccededAndNotYetCompletedFutures), ("testWhenAllCompleteWithMixOfPreSuccededAndNotYetCompletedFutures", testWhenAllCompleteWithMixOfPreSuccededAndNotYetCompletedFutures), ("testRepeatedTaskOffEventLoopGroupFuture", testRepeatedTaskOffEventLoopGroupFuture), ("testEventLoopFutureOrErrorNoThrow", testEventLoopFutureOrErrorNoThrow), ("testEventLoopFutureOrThrows", testEventLoopFutureOrThrows), ("testEventLoopFutureOrNoReplacement", testEventLoopFutureOrNoReplacement), ("testEventLoopFutureOrReplacement", testEventLoopFutureOrReplacement), ("testEventLoopFutureOrNoElse", testEventLoopFutureOrNoElse), ("testEventLoopFutureOrElse", testEventLoopFutureOrElse), ("testFlatBlockingMapOnto", testFlatBlockingMapOnto), ("testWhenSuccessBlocking", testWhenSuccessBlocking), ("testWhenFailureBlocking", testWhenFailureBlocking), ("testWhenCompleteBlockingSuccess", testWhenCompleteBlockingSuccess), ("testWhenCompleteBlockingFailure", testWhenCompleteBlockingFailure), ("testFlatMapWithEL", testFlatMapWithEL), ("testFlatMapErrorWithEL", testFlatMapErrorWithEL), ("testFoldWithEL", testFoldWithEL), ] } }
apache-2.0
stephentyrone/swift
validation-test/Reflection/reflect_Enum_TwoCaseOneStructPayload.swift
3
15751
// RUN: %empty-directory(%t) // RUN: %target-build-swift -g -lswiftSwiftReflectionTest %s -o %t/reflect_Enum_TwoCaseOneStructPayload // RUN: %target-codesign %t/reflect_Enum_TwoCaseOneStructPayload // RUN: %target-run %target-swift-reflection-test %t/reflect_Enum_TwoCaseOneStructPayload | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-ALL // REQUIRES: objc_interop // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib import SwiftReflectionTest // Note: struct Marker has no extra inhabitants, so the enum will use a separate tag struct Marker { let value = 1 } enum TwoCaseOneStructPayloadEnum { case valid(Marker) case invalid } class ClassWithTwoCaseOneStructPayloadEnum { var e1: TwoCaseOneStructPayloadEnum? var e2: TwoCaseOneStructPayloadEnum = .valid(Marker()) var e3: TwoCaseOneStructPayloadEnum = .invalid var e4: TwoCaseOneStructPayloadEnum? = .valid(Marker()) var e5: TwoCaseOneStructPayloadEnum? = .invalid var e6: TwoCaseOneStructPayloadEnum?? } reflect(object: ClassWithTwoCaseOneStructPayloadEnum()) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_Enum_TwoCaseOneStructPayload.ClassWithTwoCaseOneStructPayloadEnum) // CHECK-64: Type info: // CHECK-64: (class_instance size=107 alignment=8 stride=112 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=e1 offset=16 // CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=valid index=0 offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (case name=invalid index=1))) // CHECK-64: (case name=none index=1))) // CHECK-64: (field name=e2 offset=32 // CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=valid index=0 offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (case name=invalid index=1))) // CHECK-64: (field name=e3 offset=48 // CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=valid index=0 offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (case name=invalid index=1))) // CHECK-64: (field name=e4 offset=64 // CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=valid index=0 offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (case name=invalid index=1))) // CHECK-64: (case name=none index=1))) // CHECK-64: (field name=e5 offset=80 // CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=valid index=0 offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (case name=invalid index=1))) // CHECK-64: (case name=none index=1))) // CHECK-64: (field name=e6 offset=96 // CHECK-64: (single_payload_enum size=11 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (case name=valid index=0 offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=value offset=0 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64: (case name=invalid index=1))) // CHECK-64: (case name=none index=1))) // CHECK-64: (case name=none index=1)))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_Enum_TwoCaseOneStructPayload.ClassWithTwoCaseOneStructPayloadEnum) // CHECK-32: Type info: // CHECK-32: (class_instance size=55 alignment=4 stride=56 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=e1 offset=8 // CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=valid index=0 offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (case name=invalid index=1))) // CHECK-32: (case name=none index=1))) // CHECK-32: (field name=e2 offset=16 // CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=valid index=0 offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (case name=invalid index=1))) // CHECK-32: (field name=e3 offset=24 // CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=valid index=0 offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (case name=invalid index=1))) // CHECK-32: (field name=e4 offset=32 // CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=valid index=0 offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (case name=invalid index=1))) // CHECK-32: (case name=none index=1))) // CHECK-32: (field name=e5 offset=40 // CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=valid index=0 offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (case name=invalid index=1))) // CHECK-32: (case name=none index=1))) // CHECK-32: (field name=e6 offset=48 // CHECK-32: (single_payload_enum size=7 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (case name=valid index=0 offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=value offset=0 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32: (case name=invalid index=1))) // CHECK-32: (case name=none index=1))) // CHECK-32: (case name=none index=1)))) reflect(enum: TwoCaseOneStructPayloadEnum.valid(Marker())) // CHECK-ALL: Reflecting an enum. // CHECK-ALL-NEXT: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-ALL-NEXT: Type reference: // CHECK-ALL-NEXT: (enum reflect_Enum_TwoCaseOneStructPayload.TwoCaseOneStructPayloadEnum) // CHECK-ALL: Type info: // CHECK-64-NEXT: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (case name=valid index=0 offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (case name=invalid index=1)) // CHECK-32-NEXT: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (case name=valid index=0 offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (case name=invalid index=1)) // CHECK-ALL: Enum value: // CHECK-ALL-NEXT: (enum_value name=valid index=0 // CHECK-ALL-NEXT: (struct reflect_Enum_TwoCaseOneStructPayload.Marker) // CHECK-ALL-NEXT: ) reflect(enum: TwoCaseOneStructPayloadEnum.invalid) // CHECK-ALL: Reflecting an enum. // CHECK-ALL-NEXT: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-ALL-NEXT: Type reference: // CHECK-ALL-NEXT: (enum reflect_Enum_TwoCaseOneStructPayload.TwoCaseOneStructPayloadEnum) // CHECK-ALL: Type info: // CHECK-64-NEXT: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (case name=valid index=0 offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=value offset=0 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-64-NEXT: (case name=invalid index=1)) // CHECK-32-NEXT: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (case name=valid index=0 offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=value offset=0 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1)))))) // CHECK-32-NEXT: (case name=invalid index=1)) // CHECK-ALL: Enum value: // CHECK-ALL-NEXT: (enum_value name=invalid index=1) doneReflecting() // CHECK-ALL: Done.
apache-2.0
bracken-dev/Readability-Swift
Readability-Swift/Classes/Readability.swift
1
7599
// // Readability.swift // Readability-Swift // // Created by brackendev. // Copyright (c) 2014-2019 brackendev. All rights reserved. // // Automated Readability Index: automatedReadabilityIndexForString // Coleman–Liau Index: colemanLiauIndexForString // Flesch-Kincaid Grade Level: fleschKincaidGradeLevelForString // Flesch Reading Ease: fleschReadingEaseForString // Gunning Fog Index: gunningFogScoreForString // SMOG Grade: smogGradeForString import Foundation public class Readability { // MARK: - Automated Readability Index // http://en.wikipedia.org/wiki/Automated_Readability_Index public class func automatedReadabilityIndexForString(_ string: String) -> [String: Any] { let score = automatedReadabilityIndexScoreForString(string) let dict = ["Score": score, "Ages": automatedReadabilityIndexAgesForScore(score), "USA School Level": automatedReadabilityIndexUSASchoolLevelForScore(score)] as [String: Any] return dict } public class func automatedReadabilityIndexScoreForString(_ string: String) -> Float { let totalWords = Float(string.wordCount()) let totalSentences = Float(string.sentenceCount()) let totalAlphanumericCharacters = Float(string.alphanumericCount()) let score = 4.71 * (totalAlphanumericCharacters / totalWords) + 0.5 * (totalWords / totalSentences) - 21.43 return score.round(to: 1) } public class func automatedReadabilityIndexAgesForScore(_ score: Float) -> String { if score >= 15 { return "23+" } else if score >= 14 { return "18-22" } else if score >= 13 { return "17-18" } else if score >= 12 { return "16-17" } else if score >= 11 { return "15-16" } else if score >= 10 { return "14-15" } else if score >= 9 { return "13-14" } else if score >= 8 { return "12-13" } else if score >= 7 { return "11-12" } else if score >= 6 { return "10-11" } else if score >= 5 { return "9-10" } else if score >= 4 { return "8-9" } else if score >= 3 { return "7-8" } else if score >= 2 { return "6-7" } else { return "5-6" } } public class func automatedReadabilityIndexUSASchoolLevelForScore(_ score: Float) -> String { if score >= 14 { return "College" } else if score >= 13 { return "12" } else if score >= 12 { return "11" } else if score >= 11 { return "10" } else if score >= 10 { return "9" } else if score >= 9 { return "8" } else if score >= 8 { return "7" } else if score >= 7 { return "6" } else if score >= 6 { return "5" } else if score >= 5 { return "4" } else if score >= 4 { return "3" } else if score >= 3 { return "2" } else if score >= 2 { return "1" } else { return "Kindergarten" } } // MARK: - Coleman-Liau Index // http://en.wikipedia.org/wiki/Coleman–Liau_index public class func colemanLiauIndexForString(_ string: String) -> Float { let totalWords = Float(string.wordCount()) let totalSentences = Float(string.sentenceCount()) let totalAlphanumericCharacters = Float(string.alphanumericCount()) let score = 5.88 * (totalAlphanumericCharacters / totalWords) - 0.296 * (totalSentences / totalWords) - 15.8 return score.round(to: 1) } // MARK: - Flesch-Kincaid Grade Level // http://en.wikipedia.org/wiki/Flesch–Kincaid_readability_tests public class func fleschKincaidGradeLevelForString(_ string: String) -> Float { let totalWords = Float(string.wordCount()) let totalSentences = Float(string.sentenceCount()) let alphaNumeric = string.alphanumeric() let totalSyllables = Float(SyllableCounter.syllableCount(forWords: alphaNumeric)) let score = 0.39 * (totalWords / totalSentences) + 11.8 * (totalSyllables / totalWords) - 15.59 return score.round(to: 1) } // MARK: - Flesch Reading Ease // http://en.wikipedia.org/wiki/Flesch–Kincaid_readability_tests public class func fleschReadingEaseForString(_ string: String) -> [String: Any] { let score = fleschReadingEaseScoreForString(string) let dict = ["Score": score, "USA School Level": fleschReadingEaseUSASchoolLevelForScore(score), "Notes": fleschReadingEaseNotesForScore(score)] as [String: Any] return dict } public class func fleschReadingEaseScoreForString(_ string: String) -> Float { let totalWords = Float(string.wordCount()) let totalSentences = Float(string.sentenceCount()) let alphaNumeric = string.alphanumeric() let totalSyllables = Float(SyllableCounter.syllableCount(forWords: alphaNumeric)) let score = 206.835 - (1.015 * (totalWords / totalSentences)) - (84.6 * (totalSyllables / totalWords)) return score.round(to: 1) } public class func fleschReadingEaseUSASchoolLevelForScore(_ score: Float) -> String { if score >= 90 { return "5" } else if score >= 80 { return "6" } else if score >= 70 { return "7" } else if score >= 60 { return "8-9" } else if score >= 50 { return "10-12" } else if score >= 30 { return "College" } else { return "College Graduate" } } public class func fleschReadingEaseNotesForScore(_ score: Float) -> String { if score >= 90 { return "Very easy to read. Easily understood by an average 11-year-old student." } else if score >= 80 { return "Easy to read. Conversational English for consumers." } else if score >= 70 { return "Fairly easy to read." } else if score >= 60 { return "Plain English. Easily understood by 13- to 15-year-old students." } else if score >= 50 { return "Fairly difficult to read." } else if score >= 30 { return "Difficult to read." } else { return "Very difficult to read. Best understood by university graduates." } } // MARK: - Gunning Fog Score // http://en.wikipedia.org/wiki/Gunning_fog_index public class func gunningFogScoreForString(_ string: String) -> Float { let totalWords = Float(string.wordCount()) let totalSentences = Float(string.sentenceCount()) let totalComplexWords = Float(string.complexWordCount()) let score = 0.4 * ((totalWords / totalSentences) + 100.0 * (totalComplexWords / totalWords)) return score.round(to: 1) } // MARK: - SMOG Grade // http://en.wikipedia.org/wiki/Gunning_fog_index public class func smogGradeForString(_ string: String) -> Float { let totalPolysyllables = Float(string.polysyllableWords(excludeCommonSuffixes: false)) let totalSentences = Float(string.sentenceCount()) let score = 1.043 * sqrtf(totalPolysyllables * (30.0 / totalSentences) + 3.1291) return score.round(to: 1) } }
mit
Onetaway/Alamofire
Tests/ParameterEncodingTests.swift
1
13586
// ParameterEncodingTests.swift // // Copyright (c) 2014 Alamofire (http://alamofire.org) // // 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 XCTest extension Alamofire { struct ParameterEncodingTests { class URLParameterEncodingTestCase: XCTestCase { let encoding: ParameterEncoding = .URL var request: NSURLRequest! override func setUp() { super.setUp() let URL = NSURL(string: "http://example.com/") self.request = NSURLRequest(URL: URL) } // MARK: - func testURLParameterEncodeNilParameters() { let (request, error) = self.encoding.encode(self.request, parameters: nil) XCTAssertNil(request.URL.query?, "query should be nil") } func testURLParameterEncodeOneStringKeyStringValueParameter() { let parameters = ["foo": "bar"] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "foo=bar", "query is incorrect") } func testURLParameterEncodeOneStringKeyStringValueParameterAppendedToQuery() { var mutableRequest = self.request.mutableCopy() as NSMutableURLRequest let URLComponents = NSURLComponents(URL: mutableRequest.URL, resolvingAgainstBaseURL: false) URLComponents.query = "baz=qux" mutableRequest.URL = URLComponents.URL let parameters = ["foo": "bar"] let (request, error) = self.encoding.encode(mutableRequest, parameters: parameters) XCTAssertEqual(request.URL.query!, "baz=qux&foo=bar", "query is incorrect") } func testURLParameterEncodeTwoStringKeyStringValueParameters() { let parameters = ["foo": "bar", "baz": "qux"] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "baz=qux&foo=bar", "query is incorrect") } func testURLParameterEncodeStringKeyIntegerValueParameter() { let parameters = ["foo": 1] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "foo=1", "query is incorrect") } func testURLParameterEncodeStringKeyDoubleValueParameter() { let parameters = ["foo": 1.1] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "foo=1.1", "query is incorrect") } func testURLParameterEncodeStringKeyBoolValueParameter() { let parameters = ["foo": true] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "foo=1", "query is incorrect") } func testURLParameterEncodeStringKeyArrayValueParameter() { let parameters = ["foo": ["a", 1, true]] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "foo%5B%5D=a&foo%5B%5D=1&foo%5B%5D=1", "query is incorrect") } func testURLParameterEncodeStringKeyDictionaryValueParameter() { let parameters = ["foo": ["bar": 1]] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "foo%5Bbar%5D=1", "query is incorrect") } func testURLParameterEncodeStringKeyNestedDictionaryValueParameter() { let parameters = ["foo": ["bar": ["baz": 1]]] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "foo%5Bbar%5D%5Bbaz%5D=1", "query is incorrect") } func testURLParameterEncodeStringKeyNestedDictionaryArrayValueParameter() { let parameters = ["foo": ["bar": ["baz": ["a", 1, true]]]] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "foo%5Bbar%5D%5Bbaz%5D%5B%5D=a&foo%5Bbar%5D%5Bbaz%5D%5B%5D=1&foo%5Bbar%5D%5Bbaz%5D%5B%5D=1", "query is incorrect") } func testURLParameterEncodeStringKeyPercentEncodedStringValueParameter() { let parameters = ["percent": "%25"] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "percent=%2525", "query is incorrect") } func testURLParameterEncodeStringKeyNonLatinStringValueParameter() { let parameters = [ "french": "français", "japanese": "日本語", "arabic": "العربية", "emoji": "😃" ] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertEqual(request.URL.query!, "arabic=%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9&emoji=%F0%9F%98%83&french=fran%C3%A7ais&japanese=%E6%97%A5%E6%9C%AC%E8%AA%9E", "query is incorrect") } func testURLParameterEncodeGETParametersInURL() { var mutableRequest = self.request.mutableCopy() as NSMutableURLRequest! mutableRequest.HTTPMethod = Method.GET.toRaw() let parameters = ["foo": 1, "bar": 2] let (request, error) = self.encoding.encode(mutableRequest, parameters: parameters) XCTAssertEqual(request.URL.query!, "bar=2&foo=1", "query is incorrect") XCTAssertNil(request.valueForHTTPHeaderField("Content-Type"), "Content-Type should be nil") XCTAssertNil(request.HTTPBody, "HTTPBody should be nil") } func testURLParameterEncodePOSTParametersInHTTPBody() { var mutableRequest = self.request.mutableCopy() as NSMutableURLRequest! mutableRequest.HTTPMethod = Method.POST.toRaw() let parameters = ["foo": 1, "bar": 2] let (request, error) = self.encoding.encode(mutableRequest, parameters: parameters) XCTAssertEqual(NSString(data: request.HTTPBody, encoding: NSUTF8StringEncoding), "bar=2&foo=1", "HTTPBody is incorrect") XCTAssertEqual(request.valueForHTTPHeaderField("Content-Type")!, "application/x-www-form-urlencoded", "Content-Type should be application/x-www-form-urlencoded") XCTAssertNotNil(request.HTTPBody, "HTTPBody should not be nil") } } class JSONParameterEncodingTestCase: XCTestCase { let encoding: ParameterEncoding = .JSON(options: nil) var request: NSURLRequest! override func setUp() { super.setUp() let URL = NSURL(string: "http://example.com/") self.request = NSURLRequest(URL: URL) } // MARK: - func testJSONParameterEncodeNilParameters() { let (request, error) = self.encoding.encode(self.request, parameters: nil) XCTAssertNil(error, "error should be nil") XCTAssertNil(request.URL.query?, "query should be nil") XCTAssertNil(request.valueForHTTPHeaderField("Content-Type"), "Content-Type should be nil") XCTAssertNil(request.HTTPBody, "HTTPBody should be nil") } func testJSONParameterEncodeComplexParameters() { let parameters = [ "foo": "bar", "baz": ["a", 1, true], "qux": ["a": 1, "b": [2, 2], "c": [3, 3, 3] ] ] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertNil(error, "error should be nil") XCTAssertNil(request.URL.query?, "query should be nil") XCTAssertNotNil(request.valueForHTTPHeaderField("Content-Type"), "Content-Type should not be nil") XCTAssert(request.valueForHTTPHeaderField("Content-Type")?.hasPrefix("application/json"), "Content-Type should be application/json") XCTAssertNotNil(request.HTTPBody, "HTTPBody should not be nil") let JSON = NSJSONSerialization.JSONObjectWithData(request.HTTPBody, options: .AllowFragments, error: nil) as NSObject! XCTAssertNotNil(JSON, "HTTPBody JSON is invalid") XCTAssertEqual(JSON as NSObject, parameters as NSObject, "HTTPBody JSON does not equal parameters") } } class PropertyListParameterEncodingTestCase: XCTestCase { let encoding: ParameterEncoding = .PropertyList(format: .XMLFormat_v1_0, options: 0) var request: NSURLRequest! override func setUp() { super.setUp() let URL = NSURL(string: "http://example.com/") self.request = NSURLRequest(URL: URL) } // MARK: - func testPropertyListParameterEncodeNilParameters() { let (request, error) = self.encoding.encode(self.request, parameters: nil) XCTAssertNil(error, "error should be nil") XCTAssertNil(request.URL.query?, "query should be nil") XCTAssertNil(request.valueForHTTPHeaderField("Content-Type"), "Content-Type should be nil") XCTAssertNil(request.HTTPBody, "HTTPBody should be nil") } func testPropertyListParameterEncodeComplexParameters() { let parameters = [ "foo": "bar", "baz": ["a", 1, true], "qux": ["a": 1, "b": [2, 2], "c": [3, 3, 3] ] ] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertNil(error, "error should be nil") XCTAssertNil(request.URL.query?, "query should be nil") XCTAssertNotNil(request.valueForHTTPHeaderField("Content-Type"), "Content-Type should not be nil") XCTAssert(request.valueForHTTPHeaderField("Content-Type")?.hasPrefix("application/x-plist"), "Content-Type should be application/x-plist") XCTAssertNotNil(request.HTTPBody, "HTTPBody should not be nil") let plist = NSPropertyListSerialization.propertyListWithData(request.HTTPBody, options: 0, format: nil, error: nil) as NSObject XCTAssertNotNil(plist, "HTTPBody JSON is invalid") XCTAssertEqual(plist as NSObject, parameters as NSObject, "HTTPBody plist does not equal parameters") } func testPropertyListParameterEncodeDateAndDataParameters() { let parameters = [ "date": NSDate(), "data": "data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) ] let (request, error) = self.encoding.encode(self.request, parameters: parameters) XCTAssertNil(error, "error should be nil") XCTAssertNil(request.URL.query?, "query should be nil") XCTAssertNotNil(request.valueForHTTPHeaderField("Content-Type"), "Content-Type should not be nil") XCTAssert(request.valueForHTTPHeaderField("Content-Type")?.hasPrefix("application/x-plist"), "Content-Type should be application/x-plist") XCTAssertNotNil(request.HTTPBody, "HTTPBody should not be nil") let plist = NSPropertyListSerialization.propertyListWithData(request.HTTPBody, options: 0, format: nil, error: nil) as NSObject! XCTAssertNotNil(plist, "HTTPBody JSON is invalid") XCTAssert(plist.valueForKey("date") is NSDate, "date is not NSDate") XCTAssert(plist.valueForKey("data") is NSData, "data is not NSData") } } } }
mit
PayNoMind/iostags
Tags/SuggestionView/Cells/CompletionCell.swift
2
368
// // CompletionCell.swift // Tags // // Created by Tom Clark on 2016-06-17. // Copyright © 2016 Fluiddynamics. All rights reserved. // import UIKit class CompletionCell: UICollectionViewCell { @IBOutlet private weak var suggestedLabel: UILabel! var cellTag: Tag = Tag.tag("") var title = "" { didSet { suggestedLabel.text = title } } }
mit
mnisn/zhangchu
zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommendWidgetBtnHeaderView.swift
1
1121
// // RecommendWidgetBtnHeaderView.swift // zhangchu // // Created by 苏宁 on 2016/10/26. // Copyright © 2016年 suning. All rights reserved. // import UIKit class RecommendWidgetBtnHeaderView: UIView { var textField:UITextField! override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor(red: 243 / 255, green: 243 / 255, blue: 244 / 255, alpha: 1) // textField = UITextField(frame: CGRect(x: 35, y: 8, width: bounds.size.width - 30 * 2, height: 30)) textField.placeholder = "输入菜名或食材搜索" textField.textAlignment = .Center textField.borderStyle = .RoundedRect addSubview(textField) // let imgView = UIImageView(image: UIImage(named: "search1")) imgView.frame = CGRect(x: 0, y: 0, width: 20, height: 20) imgView.backgroundColor = UIColor.cyanColor() textField.leftView = imgView textField.leftViewMode = .Always } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
tgyhlsb/RxSwiftExt
Tests/RxSwift/notTests.swift
2
754
// // IgnoreTests.swift // RxSwiftExtDemo // // Created by Thane Gill on 10/18/16. // Copyright (c) 2016 RxSwiftCommunity https://github.com/RxSwiftCommunity // import XCTest import RxSwift import RxSwiftExt import RxTest class NotTests: XCTestCase { func testNot() { let values = [true, false, true] let scheduler = TestScheduler(initialClock: 0) let observer = scheduler.createObserver(Bool.self) _ = Observable.from(values) .not() .subscribe(observer) scheduler.start() let correct = [ next(0, false), next(0, true), next(0, false), completed(0) ] XCTAssertEqual(observer.events, correct) } }
mit
milseman/swift
test/IDE/complete_override_access_control_protocol.swift
20
12759
// RUN: sed -n -e '1,/NO_ERRORS_UP_TO_HERE$/ p' %s > %t_no_errors.swift // RUN: %target-swift-frontend -typecheck -verify -disable-objc-attr-requires-foundation-module %t_no_errors.swift // // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_PRIVATE_ABC -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PRIVATE_ABC // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_FILEPRIVATE_ABC -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PRIVATE_ABC // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_INTERNAL_ABC -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_INTERNAL_ABC // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_PUBLIC_ABC -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PUBLIC_ABC // // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_PRIVATE_DE -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PRIVATE_DE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_FILEPRIVATE_DE -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PRIVATE_DE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_INTERNAL_DE -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_INTERNAL_DE // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_PUBLIC_DE -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PUBLIC_DE // // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_PRIVATE_ED -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PRIVATE_ED // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_FILEPRIVATE_ED -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PRIVATE_ED // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_INTERNAL_ED -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_INTERNAL_ED // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_PUBLIC_ED -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PUBLIC_ED // // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_PRIVATE_EF -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PRIVATE_EF // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_FILEPRIVATE_EF -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PRIVATE_EF // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_INTERNAL_EF -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_INTERNAL_EF // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TEST_PUBLIC_EF -code-completion-keywords=false | %FileCheck %s -check-prefix=TEST_PUBLIC_EF @objc private class TagPA {} @objc class TagPB {} @objc public class TagPC {} @objc private protocol ProtocolAPrivate { init(fromProtocolA: TagPA) func protoAFunc(x: TagPA) @objc optional func protoAFuncOptional(x: TagPA) subscript(a: TagPA) -> Int { get } var protoAVarRW: TagPA { get set } var protoAVarRO: TagPA { get } } @objc protocol ProtocolBInternal { init(fromProtocolB: TagPB) func protoBFunc(x: TagPB) @objc optional func protoBFuncOptional(x: TagPB) subscript(a: TagPB) -> Int { get } var protoBVarRW: TagPB { get set } var protoBVarRO: TagPB { get } } @objc public protocol ProtocolCPublic { init(fromProtocolC: TagPC) func protoCFunc(x: TagPC) @objc optional func protoCFuncOptional(x: TagPC) subscript(a: TagPC) -> Int { get } var protoCVarRW: TagPC { get set } var protoCVarRO: TagPC { get } } private protocol ProtocolDPrivate { func colliding() func collidingGeneric<T>(x: T) } public protocol ProtocolEPublic { func colliding() func collidingGeneric<T>(x: T) } public protocol ProtocolFPublic { func colliding() func collidingGeneric<T>(x: T) } // NO_ERRORS_UP_TO_HERE private class TestPrivateABC : ProtocolAPrivate, ProtocolBInternal, ProtocolCPublic { #^TEST_PRIVATE_ABC^# } fileprivate class TestFilePrivateABC : ProtocolAPrivate, ProtocolBInternal, ProtocolCPublic { #^TEST_FILEPRIVATE_ABC^# // Same as TEST_PRIVATE_ABC. } class TestInternalABC : ProtocolAPrivate, ProtocolBInternal, ProtocolCPublic { #^TEST_INTERNAL_ABC^# } public class TestPublicABC : ProtocolAPrivate, ProtocolBInternal, ProtocolCPublic { #^TEST_PUBLIC_ABC^# } // TEST_PRIVATE_ABC: Begin completions, 15 items // TEST_PRIVATE_ABC-DAG: Decl[Constructor]/Super: required init(fromProtocolA: TagPA) {|}{{; name=.+$}} // TEST_PRIVATE_ABC-DAG: Decl[InstanceMethod]/Super: func protoAFunc(x: TagPA) {|}{{; name=.+$}} // TEST_PRIVATE_ABC-DAG: Decl[InstanceMethod]/Super: func protoAFuncOptional(x: TagPA) {|}{{; name=.+$}} // TEST_PRIVATE_ABC-DAG: Decl[Constructor]/Super: required init(fromProtocolB: TagPB) {|}{{; name=.+$}} // TEST_PRIVATE_ABC-DAG: Decl[InstanceMethod]/Super: func protoBFunc(x: TagPB) {|}{{; name=.+$}} // TEST_PRIVATE_ABC-DAG: Decl[InstanceMethod]/Super: func protoBFuncOptional(x: TagPB) {|}{{; name=.+$}} // TEST_PRIVATE_ABC-DAG: Decl[Constructor]/Super: required init(fromProtocolC: TagPC) {|}{{; name=.+$}} // TEST_PRIVATE_ABC-DAG: Decl[InstanceMethod]/Super: func protoCFunc(x: TagPC) {|}{{; name=.+$}} // TEST_PRIVATE_ABC-DAG: Decl[InstanceMethod]/Super: func protoCFuncOptional(x: TagPC) {|}{{; name=.+$}} // TEST_PRIVATE_ABC-DAG: Decl[InstanceVar]/Super: var protoAVarRW: TagPA // TEST_PRIVATE_ABC-DAG: Decl[InstanceVar]/Super: var protoAVarRO: TagPA // TEST_PRIVATE_ABC-DAG: Decl[InstanceVar]/Super: var protoBVarRW: TagPB // TEST_PRIVATE_ABC-DAG: Decl[InstanceVar]/Super: var protoBVarRO: TagPB // TEST_PRIVATE_ABC-DAG: Decl[InstanceVar]/Super: var protoCVarRW: TagPC // TEST_PRIVATE_ABC-DAG: Decl[InstanceVar]/Super: var protoCVarRO: TagPC // TEST_PRIVATE_ABC: End completions // TEST_INTERNAL_ABC: Begin completions, 15 items // TEST_INTERNAL_ABC-DAG: Decl[Constructor]/Super: required init(fromProtocolA: TagPA) {|}{{; name=.+$}} // TEST_INTERNAL_ABC-DAG: Decl[InstanceMethod]/Super: func protoAFunc(x: TagPA) {|}{{; name=.+$}} // TEST_INTERNAL_ABC-DAG: Decl[InstanceMethod]/Super: func protoAFuncOptional(x: TagPA) {|}{{; name=.+$}} // TEST_INTERNAL_ABC-DAG: Decl[Constructor]/Super: required init(fromProtocolB: TagPB) {|}{{; name=.+$}} // TEST_INTERNAL_ABC-DAG: Decl[InstanceMethod]/Super: func protoBFunc(x: TagPB) {|}{{; name=.+$}} // TEST_INTERNAL_ABC-DAG: Decl[InstanceMethod]/Super: func protoBFuncOptional(x: TagPB) {|}{{; name=.+$}} // TEST_INTERNAL_ABC-DAG: Decl[Constructor]/Super: required init(fromProtocolC: TagPC) {|}{{; name=.+$}} // TEST_INTERNAL_ABC-DAG: Decl[InstanceMethod]/Super: func protoCFunc(x: TagPC) {|}{{; name=.+$}} // TEST_INTERNAL_ABC-DAG: Decl[InstanceMethod]/Super: func protoCFuncOptional(x: TagPC) {|}{{; name=.+$}} // TEST_INTERNAL_ABC-DAG: Decl[InstanceVar]/Super: var protoAVarRW: TagPA // TEST_INTERNAL_ABC-DAG: Decl[InstanceVar]/Super: var protoAVarRO: TagPA // TEST_INTERNAL_ABC-DAG: Decl[InstanceVar]/Super: var protoBVarRW: TagPB // TEST_INTERNAL_ABC-DAG: Decl[InstanceVar]/Super: var protoBVarRO: TagPB // TEST_INTERNAL_ABC-DAG: Decl[InstanceVar]/Super: var protoCVarRW: TagPC // TEST_INTERNAL_ABC-DAG: Decl[InstanceVar]/Super: var protoCVarRO: TagPC // TEST_INTERNAL_ABC: End completions // TEST_PUBLIC_ABC: Begin completions, 15 items // TEST_PUBLIC_ABC-DAG: Decl[Constructor]/Super: required init(fromProtocolA: TagPA) {|}{{; name=.+$}} // TEST_PUBLIC_ABC-DAG: Decl[InstanceMethod]/Super: func protoAFunc(x: TagPA) {|}{{; name=.+$}} // TEST_PUBLIC_ABC-DAG: Decl[InstanceMethod]/Super: func protoAFuncOptional(x: TagPA) {|}{{; name=.+$}} // TEST_PUBLIC_ABC-DAG: Decl[Constructor]/Super: required init(fromProtocolB: TagPB) {|}{{; name=.+$}} // TEST_PUBLIC_ABC-DAG: Decl[InstanceMethod]/Super: func protoBFunc(x: TagPB) {|}{{; name=.+$}} // TEST_PUBLIC_ABC-DAG: Decl[InstanceMethod]/Super: func protoBFuncOptional(x: TagPB) {|}{{; name=.+$}} // TEST_PUBLIC_ABC-DAG: Decl[Constructor]/Super: public required init(fromProtocolC: TagPC) {|}{{; name=.+$}} // TEST_PUBLIC_ABC-DAG: Decl[InstanceMethod]/Super: public func protoCFunc(x: TagPC) {|}{{; name=.+$}} // TEST_PUBLIC_ABC-DAG: Decl[InstanceMethod]/Super: public func protoCFuncOptional(x: TagPC) {|}{{; name=.+$}} // TEST_PUBLIC_ABC-DAG: Decl[InstanceVar]/Super: var protoAVarRW: TagPA // TEST_PUBLIC_ABC-DAG: Decl[InstanceVar]/Super: var protoAVarRO: TagPA // TEST_PUBLIC_ABC-DAG: Decl[InstanceVar]/Super: var protoBVarRW: TagPB // TEST_PUBLIC_ABC-DAG: Decl[InstanceVar]/Super: var protoBVarRO: TagPB // TEST_PUBLIC_ABC-DAG: Decl[InstanceVar]/Super: public var protoCVarRW: TagPC // TEST_PUBLIC_ABC-DAG: Decl[InstanceVar]/Super: public var protoCVarRO: TagPC // TEST_PUBLIC_ABC: End completions private class TestPrivateDE : ProtocolDPrivate, ProtocolEPublic { #^TEST_PRIVATE_DE^# } fileprivate class TestPrivateDE : ProtocolDPrivate, ProtocolEPublic { #^TEST_FILEPRIVATE_DE^# // Same as TEST_PRIVATE_DE. } class TestInternalDE : ProtocolDPrivate, ProtocolEPublic { #^TEST_INTERNAL_DE^# } public class TestPublicDE : ProtocolDPrivate, ProtocolEPublic { #^TEST_PUBLIC_DE^# } // FIXME: Should be 2 items in the three checks below. // TEST_PRIVATE_DE: Begin completions, 4 items // TEST_PRIVATE_DE-DAG: Decl[InstanceMethod]/Super: func colliding() {|}{{; name=.+$}} // TEST_PRIVATE_DE-DAG: Decl[InstanceMethod]/Super: func collidingGeneric<T>(x: T) {|}{{; name=.+$}} // TEST_INTERNAL_DE: Begin completions, 4 items // TEST_INTERNAL_DE-DAG: Decl[InstanceMethod]/Super: func colliding() {|}{{; name=.+$}} // TEST_INTERNAL_DE-DAG: Decl[InstanceMethod]/Super: func collidingGeneric<T>(x: T) {|}{{; name=.+$}} // TEST_PUBLIC_DE: Begin completions, 4 items // TEST_PUBLIC_DE-DAG: Decl[InstanceMethod]/Super: public func colliding() {|}{{; name=.+$}} // TEST_PUBLIC_DE-DAG: Decl[InstanceMethod]/Super: public func collidingGeneric<T>(x: T) {|}{{; name=.+$}} private class TestPrivateED : ProtocolEPublic, ProtocolDPrivate { #^TEST_PRIVATE_ED^# } fileprivate class TestPrivateED : ProtocolEPublic, ProtocolDPrivate { #^TEST_FILEPRIVATE_ED^# // Same as TEST_PRIVATE_ED. } class TestInternalED : ProtocolEPublic, ProtocolDPrivate { #^TEST_INTERNAL_ED^# } public class TestPublicED : ProtocolEPublic, ProtocolDPrivate { #^TEST_PUBLIC_ED^# } // FIXME: Should be 2 items in the three checks below. // TEST_PRIVATE_ED: Begin completions, 4 items // TEST_PRIVATE_ED-DAG: Decl[InstanceMethod]/Super: func colliding() {|}{{; name=.+$}} // TEST_PRIVATE_ED-DAG: Decl[InstanceMethod]/Super: func collidingGeneric<T>(x: T) {|}{{; name=.+$}} // TEST_INTERNAL_ED: Begin completions, 4 items // TEST_INTERNAL_ED-DAG: Decl[InstanceMethod]/Super: func collidingGeneric<T>(x: T) {|}{{; name=.+$}} // TEST_INTERNAL_ED-DAG: Decl[InstanceMethod]/Super: func colliding() {|}{{; name=.+$}} // TEST_PUBLIC_ED: Begin completions, 4 items // TEST_PUBLIC_ED-DAG: Decl[InstanceMethod]/Super: public func collidingGeneric<T>(x: T) {|}{{; name=.+$}} // TEST_PUBLIC_ED-DAG: Decl[InstanceMethod]/Super: public func colliding() {|}{{; name=.+$}} private class TestPrivateEF : ProtocolEPublic, ProtocolFPublic { #^TEST_PRIVATE_EF^# } fileprivate class TestPrivateEF : ProtocolEPublic, ProtocolFPublic { #^TEST_FILEPRIVATE_EF^# // Same as TEST_PRIVATE_EF. } class TestInternalEF : ProtocolEPublic, ProtocolFPublic { #^TEST_INTERNAL_EF^# } public class TestPublicEF : ProtocolEPublic, ProtocolFPublic { #^TEST_PUBLIC_EF^# } // FIXME: Should be 2 items in the three checks below. // TEST_PRIVATE_EF: Begin completions, 4 items // TEST_PRIVATE_EF-DAG: Decl[InstanceMethod]/Super: func colliding() {|}{{; name=.+$}} // TEST_PRIVATE_EF-DAG: Decl[InstanceMethod]/Super: func collidingGeneric<T>(x: T) {|}{{; name=.+$}} // TEST_INTERNAL_EF: Begin completions, 4 items // TEST_INTERNAL_EF-DAG: Decl[InstanceMethod]/Super: func colliding() {|}{{; name=.+$}} // TEST_INTERNAL_EF-DAG: Decl[InstanceMethod]/Super: func collidingGeneric<T>(x: T) {|}{{; name=.+$}} // TEST_PUBLIC_EF: Begin completions, 4 items // TEST_PUBLIC_EF-DAG: Decl[InstanceMethod]/Super: public func colliding() {|}{{; name=.+$}} // TEST_PUBLIC_EF-DAG: Decl[InstanceMethod]/Super: public func collidingGeneric<T>(x: T) {|}{{; name=.+$}}
apache-2.0
LibraryLoupe/PhotosPlus
PhotosPlus/Cameras/Sony/SonyAlphaNEX3N.swift
3
502
// // Photos Plus, https://github.com/LibraryLoupe/PhotosPlus // // Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved. // import Foundation extension Cameras.Manufacturers.Sony { public struct AlphaNEX3N: CameraModel { public init() {} public let name = "Sony Alpha NEX-3N" public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Sony.self } } public typealias SonyAlphaNEX3N = Cameras.Manufacturers.Sony.AlphaNEX3N
mit
josefdolezal/iconic
Sources/Iconic/extensions/IconFont+ArgumentConvertible.swift
1
494
// // IconFont+ArgumentConvertible.swift // Iconic // // Created by Josef Dolezal on 19/05/2017. // // import Commander import PathKit import IconicKit extension IconFont: ArgumentConvertible { public init(parser: ArgumentParser) throws { let path = try Path(parser: parser) do { try self.init(path: path) } catch { throw ArgumentError.invalidType(value: path.description, type: "otf or ttf font file", argument: nil) } } }
mit
cojoj/XcodeServerSDK
XcodeServerSDK/XcodeServer.swift
1
6179
// // XcodeServer.swift // Buildasaur // // Created by Honza Dvorsky on 14/12/2014. // Copyright (c) 2014 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils // MARK: XcodeServer Class public class XcodeServer : CIServer { public let config: XcodeServerConfig let endpoints: XcodeServerEndpoints public init(config: XcodeServerConfig, endpoints: XcodeServerEndpoints) { self.config = config self.endpoints = endpoints super.init() let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration() let delegate: NSURLSessionDelegate = self let queue = NSOperationQueue.mainQueue() let session = NSURLSession(configuration: sessionConfig, delegate: delegate, delegateQueue: queue) self.http.session = session } } // MARK: NSURLSession delegate implementation extension XcodeServer : NSURLSessionDelegate { var credential: NSURLCredential? { if let user = self.config.user, let password = self.config.password { return NSURLCredential(user: user, password: password, persistence: NSURLCredentialPersistence.None) } return nil } public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential? if challenge.previousFailureCount > 0 { disposition = .CancelAuthenticationChallenge } else { switch challenge.protectionSpace.authenticationMethod { case NSURLAuthenticationMethodServerTrust: credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!) default: credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace) } if credential != nil { disposition = .UseCredential } } completionHandler(disposition, credential) } } // MARK: Header constants let Headers_APIVersion = "X-XCSAPIVersion" let SupportedAPIVersion: Int = 6 //will change with time, this codebase supports this version // MARK: XcodeServer API methods public extension XcodeServer { private func verifyAPIVersion(response: NSHTTPURLResponse) -> NSError? { guard let headers = response.allHeaderFields as? [String: AnyObject] else { return Error.withInfo("No headers provided in response") } let apiVersionString = (headers[Headers_APIVersion] as? String) ?? "-1" let apiVersion = Int(apiVersionString) if apiVersion > 0 && SupportedAPIVersion != apiVersion { var common = "Version mismatch: response from API version \(apiVersion), but we support version \(SupportedAPIVersion). " if apiVersion > SupportedAPIVersion { common += "You're using a newer Xcode Server than we support. Please visit https://github.com/czechboy0/XcodeServerSDK to check whether there's a new version of the SDK for it." } else { common += "You're using an old Xcode Server which we don't support any more. Please look for an older version of the SDK at https://github.com/czechboy0/XcodeServerSDK or consider upgrading your Xcode Server to the current version." } return Error.withInfo(common) } //all good return nil } /** Internal usage generic method for sending HTTP requests. - parameter method: HTTP method. - parameter endpoint: API endpoint. - parameter params: URL paramaters. - parameter query: URL query. - parameter body: POST method request body. - parameter completion: Completion. */ internal func sendRequestWithMethod(method: HTTP.Method, endpoint: XcodeServerEndpoints.Endpoint, params: [String: String]?, query: [String: String]?, body: NSDictionary?, portOverride: Int? = nil, completion: HTTP.Completion) -> NSURLSessionTask? { if let request = self.endpoints.createRequest(method, endpoint: endpoint, params: params, query: query, body: body, portOverride: portOverride) { return self.http.sendRequest(request, completion: { (response, body, error) -> () in //TODO: fix hack, make completion always return optionals let resp: NSHTTPURLResponse? = response guard let r = resp else { let e = error ?? Error.withInfo("Nil response") completion(response: nil, body: body, error: e) return } if let versionError = self.verifyAPIVersion(r) { completion(response: response, body: body, error: versionError) return } if case (200...299) = r.statusCode { //pass on completion(response: response, body: body, error: error) } else { //see if we haven't received a XCS failure in headers if let xcsStatusMessage = r.allHeaderFields["X-XCSResponse-Status-Message"] as? String { let e = Error.withInfo(xcsStatusMessage) completion(response: response, body: body, error: e) } else { completion(response: response, body: body, error: error) } } }) } else { completion(response: nil, body: nil, error: Error.withInfo("Couldn't create Request")) return nil } } }
mit
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_/PartialViews/TextFields/NormalTextField.swift
2
1364
// // NormalTextField.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 30/10/16. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit class NormalTextField: BaseTextField { }
mit
Friend-LGA/LGSideMenuController
Demo/_shared_files/SideMenuController/RightViewController/RightViewCellHeaderView.swift
1
858
// // RightViewCellHeaderView.swift // LGSideMenuControllerDemo // import Foundation import UIKit class RightViewCellHeaderView: UIView { init() { super.init(frame: .zero) backgroundColor = .clear } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } context.clear(rect) context.setFillColor(UIColor(white: 1.0, alpha: 0.3).cgColor) let offset: CGFloat = 16.0 let height: CGFloat = 4.0 context.fill(CGRect(x: offset, y: rect.height / 2.0 - height / 2.0, width: rect.width - offset, height: height)) } }
mit
codefellows/sea-b23-iOS
Hipstagram/Hipstagram/ThumbnailCell.swift
1
263
// // ThumbnailCell.swift // Hipstagram // // Created by Bradley Johnson on 10/15/14. // Copyright (c) 2014 Code Fellows. All rights reserved. // import UIKit class ThumbnailCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! }
mit
takezou621/PaintCodeSwiftTest
PaintCodeSwiftTest/ViewController.swift
1
524
// // ViewController.swift // PaintCodeSwiftTest // // Created by KawaiTakeshi on 2014/10/03. // Copyright (c) 2014年 KawaiTakeshi. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
HabitRPG/habitrpg-ios
Habitica Database/Habitica Database/Models/Content/RealmCustomization.swift
1
1332
// // RealmCustomization.swift // Habitica Database // // Created by Phillip Thelen on 20.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import RealmSwift class RealmCustomization: Object, CustomizationProtocol { @objc dynamic var combinedKey: String? @objc dynamic var key: String? @objc dynamic var type: String? @objc dynamic var group: String? @objc dynamic var price: Float = 0 var set: CustomizationSetProtocol? { get { return realmSet } set { if let newSet = newValue as? RealmCustomizationSet { realmSet = newSet } else if let newSet = newValue { realmSet = RealmCustomizationSet(newSet) } } } @objc dynamic var realmSet: RealmCustomizationSet? override static func primaryKey() -> String { return "combinedKey" } convenience init(_ customizationProtocol: CustomizationProtocol) { self.init() key = customizationProtocol.key type = customizationProtocol.type group = customizationProtocol.group combinedKey = (key ?? "") + (type ?? "") + (group ?? "") price = customizationProtocol.price set = customizationProtocol.set } }
gpl-3.0
dataich/TypetalkSwift
Carthage/Checkouts/OAuth2/Tests/FlowTests/OAuth2RefreshTokenTests.swift
1
3715
// // OAuth2RefreshTokenTests.swift // OAuth2 // // Created by Pascal Pfiffner on 12/20/15. // Copyright © 2015 Pascal Pfiffner. 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 XCTest #if !NO_MODULE_IMPORT @testable import Base @testable import Flows #else @testable import OAuth2 #endif class OAuth2RefreshTokenTests: XCTestCase { func genericOAuth2() -> OAuth2 { return OAuth2(settings: [ "client_id": "abc", "authorize_uri": "https://auth.ful.io", "token_uri": "https://token.ful.io", "keychain": false, ]) } func testCannotRefresh() { let oauth = genericOAuth2() do { _ = try oauth.tokenRequestForTokenRefresh().asURLRequest(for: oauth) XCTAssertTrue(false, "Should throw when trying to create refresh token request without refresh token") } catch OAuth2Error.noRefreshToken { } catch { XCTAssertTrue(false, "Should have thrown `NoRefreshToken`") } } func testRefreshRequest() { let oauth = genericOAuth2() oauth.clientConfig.refreshToken = "pov" let req = try? oauth.tokenRequestForTokenRefresh().asURLRequest(for: oauth) XCTAssertNotNil(req) XCTAssertNotNil(req?.url) XCTAssertNotNil(req?.httpBody) XCTAssertEqual("https://token.ful.io", req!.url!.absoluteString) let comp = URLComponents(url: req!.url!, resolvingAgainstBaseURL: true) let params = comp?.percentEncodedQuery XCTAssertNil(params) let body = String(data: req!.httpBody!, encoding: String.Encoding.utf8) XCTAssertNotNil(body) let dict = OAuth2.params(fromQuery: body!) XCTAssertEqual(dict["client_id"], "abc") XCTAssertEqual(dict["refresh_token"], "pov") XCTAssertEqual(dict["grant_type"], "refresh_token") XCTAssertNil(dict["client_secret"]) XCTAssertNil(req!.allHTTPHeaderFields?["Authorization"]) } func testRefreshRequestWithSecret() { let oauth = genericOAuth2() oauth.clientConfig.refreshToken = "pov" oauth.clientConfig.clientSecret = "uvw" let req = try? oauth.tokenRequestForTokenRefresh().asURLRequest(for: oauth) XCTAssertNotNil(req) XCTAssertNotNil(req?.httpBody) let body = String(data: req!.httpBody!, encoding: String.Encoding.utf8) XCTAssertNotNil(body) let dict = OAuth2.params(fromQuery: body!) XCTAssertNil(dict["client_id"]) XCTAssertNil(dict["client_secret"]) let auth = req!.allHTTPHeaderFields?["Authorization"] XCTAssertNotNil(auth) XCTAssertEqual("Basic YWJjOnV2dw==", auth, "Expecting correctly base64-encoded Authorization header") } func testRefreshRequestWithSecretInBody() { let oauth = genericOAuth2() oauth.clientConfig.refreshToken = "pov" oauth.clientConfig.clientSecret = "uvw" oauth.clientConfig.secretInBody = true let req = try? oauth.tokenRequestForTokenRefresh(params: ["param": "fool"]).asURLRequest(for: oauth) XCTAssertNotNil(req) XCTAssertNotNil(req?.httpBody) let body = String(data: req!.httpBody!, encoding: String.Encoding.utf8) XCTAssertNotNil(body) let dict = OAuth2.params(fromQuery: body!) XCTAssertEqual(dict["client_id"], "abc") XCTAssertEqual(dict["client_secret"], "uvw") XCTAssertEqual(dict["param"], "fool") XCTAssertNil(req!.allHTTPHeaderFields?["Authorization"]) } }
mit
instructure/CanvasKit
CanvasKitTests/Networking Tests/CKIPollChoiceNetworkingTests.swift
3
1884
// // CKIPollChoiceNetworkingTests.swift // CanvasKit // // Created by Nathan Lambson on 7/29/14. // Copyright (c) 2014 Instructure. All rights reserved. // import XCTest class CKIPollChoiceNetworkingTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testFetchPollChoicesForPoll() { let client = MockCKIClient() let pollDictionary = Helpers.loadJSONFixture("poll") as NSDictionary let poll = CKIPoll(fromJSONDictionary: pollDictionary) client.fetchPollChoicesForPoll(poll) XCTAssertEqual(client.capturedPath!, "/api/v1/polls/1023/poll_choices", "CKIPollChoice returned API path for testFetchPollCHoicesForPoll was incorrect") XCTAssertEqual(client.capturedMethod!, MockCKIClient.Method.Fetch, "CKIPollChoice API Interaction Method was incorrect") } func testCreatePollChoice() { let client = MockCKIClient() let pollChoiceDictionary = Helpers.loadJSONFixture("poll_choice") as NSDictionary let pollChoice = CKIPollChoice(fromJSONDictionary: pollChoiceDictionary) let pollDictionary = Helpers.loadJSONFixture("poll") as NSDictionary let poll = CKIPoll(fromJSONDictionary: pollDictionary) client.createPollChoice(pollChoice, forPoll: poll) XCTAssertEqual(client.capturedPath!, "/api/v1/polls/1023/poll_choices", "CKIPollChoice returned API path for testCreatePollChoice was incorrect") XCTAssertEqual(client.capturedMethod!, MockCKIClient.Method.Create, "CKIPollChoice API Interaction Method was incorrect") } }
mit
Driftt/drift-sdk-ios
Drift/Managers/PresentationManager.swift
1
3703
// // PresentationManager.swift // Drift // // Created by Eoin O'Connell on 26/01/2016. // Copyright © 2016 Drift. All rights reserved. // import UIKit protocol PresentationManagerDelegate:class { func messageViewDidFinish(_ view: CampaignView) } ///Responsible for showing a campaign class PresentationManager: PresentationManagerDelegate { static var sharedInstance: PresentationManager = PresentationManager() weak var currentShownView: CampaignView? private var shouldShowMessagePopup = true init () {} func shouldShowMessagePopup(show: Bool) { shouldShowMessagePopup = show } func didRecieveNewMessages(_ enrichedConversations: [EnrichedConversation]) { guard shouldShowMessagePopup else { return } if let newMessageView = NewMessageView.drift_fromNib() as? NewMessageView , currentShownView == nil && !conversationIsPresenting() && !enrichedConversations.isEmpty{ if let window = UIApplication.shared.keyWindow { currentShownView = newMessageView if let currentConversation = enrichedConversations.first, let lastMessage = currentConversation.lastMessage { let otherConversations = enrichedConversations.filter({ $0.conversation.id != currentConversation.conversation.id }) newMessageView.otherConversations = otherConversations newMessageView.message = lastMessage newMessageView.delegate = self newMessageView.showOnWindow(window) } } } } func didRecieveNewMessage(_ message: Message) { guard shouldShowMessagePopup else { return } if let newMessageView = NewMessageView.drift_fromNib() as? NewMessageView , currentShownView == nil && !conversationIsPresenting() { if let window = UIApplication.shared.keyWindow { currentShownView = newMessageView newMessageView.message = message newMessageView.delegate = self newMessageView.showOnWindow(window) } } } func conversationIsPresenting() -> Bool{ if let topVC = TopController.viewController() , topVC.classForCoder == ConversationListViewController.classForCoder() || topVC.classForCoder == ConversationViewController.classForCoder(){ return true } return false } func showConversationList(endUserId: Int64?){ let conversationListController = ConversationListViewController.navigationController(endUserId: endUserId) TopController.viewController()?.present(conversationListController, animated: true, completion: nil) } func showConversationVC(_ conversationId: Int64) { if let topVC = TopController.viewController() { let navVC = ConversationViewController.navigationController(ConversationViewController.ConversationType.continueConversation(conversationId: conversationId)) topVC.present(navVC, animated: true, completion: nil) } } func showNewConversationVC(initialMessage: String? = nil) { if let topVC = TopController.viewController() { let navVC = ConversationViewController.navigationController(ConversationViewController.ConversationType.createConversation, initialMessage: initialMessage) topVC.present(navVC, animated: true) } } ///Presentation Delegate func messageViewDidFinish(_ view: CampaignView) { view.hideFromWindow() currentShownView = nil } }
mit
Rehsco/StyledAuthenticationView
StyledAuthenticationView/UI/Styling/StyledAuthenticationViewConfiguration.swift
1
3447
// // StyledAuthenticationViewConfiguration.swift // StyledAuthenticationView // // Created by Martin Rehder on 16.02.2019. /* * Copyright 2017-present Martin Jacob Rehder. * http://www.rehsco.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 import FlexCollections import FlexControls public class StyledAuthenticationViewConfiguration { public init() { } // Touch ID public var touchIDDetailText = "Authentication using Touch ID" // PIN public var pinHeaderText = "Enter PIN Code" public var usePinCodeText = "Use PIN Code" public var createPinHeaderText = "Enter new PIN Code" public var verifyPinHeaderText = "Verify PIN Code" public var expectedPinCodeLength = 6 // Password public var passwordHeaderText = "Enter Password" public var createPasswordHeaderText = "Enter new Password" public var verifyPasswordHeaderText = "Verify Password" // Options public var vibrateOnFail = true public var allowedRetries = 3 public var showCancel = true // Styling public var securityViewPreferredSize: CGSize = CGSize(width: 300, height: 480) public var pinCellPreferredSize: CGSize = CGSize(width: 80, height: 80) public var microPinViewHeight: CGFloat = 75 public var pinViewFooterHeight: CGFloat = 25 public var passwordViewHeight: CGFloat = 120 public var pinStyle: FlexShapeStyle = FlexShapeStyle(style: .thumb) public var pinBorderColor: UIColor = .white public var pinSelectionColor: UIColor = .white public var pinInnerColor: UIColor = .clear public var pinBorderWidth: CGFloat = 0.5 public var pinTextColor: UIColor = .white public var pinFont: UIFont = UIFont.systemFont(ofSize: 36) public var cancelDeleteButtonFont: UIFont = UIFont.systemFont(ofSize: 18) public var cancelDeleteButtonTextColor: UIColor = .white public var headerTextColor: UIColor = .white public var headerTextFont: UIFont = UIFont.systemFont(ofSize: 18) public var passwordStyle: FlexShapeStyle = FlexShapeStyle(style: .box) public var passwordBorderColor: UIColor = .white public var passwordAcceptButtonIcon: UIImage? = UIImage(named: "Accept_36pt", in: Bundle(for: StyledAuthenticationViewConfiguration.self), compatibleWith: nil) public var backgroundGradientStartColor: UIColor? public var backgroundGradientEndColor: UIColor? }
mit
AutomationStation/BouncerBuddy
BouncerBuddyV6/BouncerBuddy/AfterCompareViewController.swift
1
609
// // AfterCompareViewController.swift // BouncerBuddy // // Created by Sha Wu on 16/4/11. // Copyright © 2016年 Sheryl Hong. All rights reserved. // import UIKit class AfterCompareViewController: UIViewController{ @IBOutlet var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
AmitaiB/MyPhotoViewer
Pods/Cache/Source/Shared/Configuration/MemoryConfig.swift
1
682
import Foundation public struct MemoryConfig { /// Expiry date that will be applied by default for every added object /// if it's not overridden in the add(key: object: expiry: completion:) method public let expiry: Expiry /// The maximum number of objects in memory the cache should hold. 0 means no limit. public let countLimit: UInt /// The maximum total cost that the cache can hold before it starts evicting objects. 0 means no limit. public let totalCostLimit: UInt public init(expiry: Expiry = .never, countLimit: UInt = 0, totalCostLimit: UInt = 0) { self.expiry = expiry self.countLimit = countLimit self.totalCostLimit = totalCostLimit } }
mit
sschiau/swift
test/DebugInfo/enum.swift
2
3312
// RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | %FileCheck %s // RUN: %target-swift-frontend -primary-file %s -emit-ir -gdwarf-types -o - | %FileCheck %s --check-prefix=DWARF // UNSUPPORTED: OS=watchos protocol P {} enum Either { case First(Int64), Second(P), Neither // CHECK: !DICompositeType({{.*}}name: "Either", // CHECK-SAME: line: [[@LINE-3]], // CHECK-SAME: size: {{328|168}}, } // CHECK: ![[EMPTY:.*]] = !{} // DWARF: ![[INT:.*]] = !DICompositeType({{.*}}identifier: "$sSiD" let E : Either = .Neither; // CHECK: !DICompositeType({{.*}}name: "Color", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: size: 8, // CHECK-SAME: identifier: "$s4enum5ColorOD" enum Color : UInt64 { // This is effectively a 2-bit bitfield: // DWARF: !DIDerivedType(tag: DW_TAG_member, name: "Red" // DWARF-SAME: baseType: ![[UINT64:[0-9]+]] // DWARF-SAME: size: 8{{[,)]}} // DWARF: ![[UINT64]] = !DICompositeType({{.*}}identifier: "$ss6UInt64VD" case Red, Green, Blue } // CHECK: !DICompositeType({{.*}}name: "MaybeIntPair", // CHECK-SAME: line: [[@LINE+3]], // CHECK-SAME: size: 136{{[,)]}} // CHECK-SAME: identifier: "$s4enum12MaybeIntPairOD" enum MaybeIntPair { // DWARF: !DIDerivedType(tag: DW_TAG_member, name: "none" // DWARF-SAME: baseType: ![[INT]]{{[,)]}} case none // DWARF: !DIDerivedType(tag: DW_TAG_member, name: "just" // DWARF-SAME: baseType: ![[INTTUP:[0-9]+]] // DWARF-SAME: size: 128{{[,)]}} // DWARF: ![[INTTUP]] = !DICompositeType({{.*}}identifier: "$ss5Int64V_ABtD" case just(Int64, Int64) } enum Maybe<T> { case none case just(T) } let r = Color.Red let c = MaybeIntPair.just(74, 75) // CHECK: !DICompositeType({{.*}}name: "Maybe", // CHECK-SAME: line: [[@LINE-8]], // CHECK-SAME: size: 8{{[,)]}} // CHECK-SAME: identifier: "$s4enum5MaybeOyAA5ColorOGD" let movie : Maybe<Color> = .none public enum Nothing { } public func foo(_ empty : Nothing) { } // CHECK: !DICompositeType({{.*}}name: "Nothing", {{.*}}elements: ![[EMPTY]] // CHECK: !DICompositeType({{.*}}name: "Rose", {{.*}}elements: ![[ELTS:[0-9]+]], // CHECK-SAME: {{.*}}identifier: "$s4enum4RoseOyxG{{z?}}D") enum Rose<A> { case MkRose(() -> A, () -> [Rose<A>]) // DWARF: !DICompositeType({{.*}}name: "Rose",{{.*}}identifier: "$s4enum4RoseOyxGD") case IORose(() -> Rose<A>) } func foo<T>(_ x : Rose<T>) -> Rose<T> { return x } // CHECK: !DICompositeType({{.*}}name: "Tuple", {{.*}}elements: ![[ELTS:[0-9]+]], {{.*}}identifier: "$s4enum5TupleOyxGD") // DWARF: !DICompositeType({{.*}}name: "Tuple", {{.*}}elements: ![[ELTS:[0-9]+]], // DWARF-SAME: {{.*}}identifier: "$s4enum5TupleOyxG{{z?}}D") public enum Tuple<P> { case C(P, () -> Tuple) } func bar<T>(_ x : Tuple<T>) -> Tuple<T> { return x } // CHECK: ![[LIST:.*]] = !DICompositeType({{.*}}identifier: "$s4enum4ListOyxGD" // CHECK-DAG: ![[LET_LIST:.*]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[LIST]]) // CHECK-DAG: !DILocalVariable(name: "self", arg: 1, {{.*}} line: [[@LINE+4]], type: ![[LET_LIST]], flags: DIFlagArtificial) public enum List<T> { indirect case Tail(List, T) case End func fooMyList() {} }
apache-2.0
nickoneill/PermissionScope
PermissionScope-example/AppDelegate.swift
2
2194
// // AppDelegate.swift // PermissionScope-example // // Created by Nick O'Neill on 4/5/15. // Copyright (c) 2015 That Thing in Swift. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } }
mit
apple/swift-driver
Sources/SwiftDriver/IncrementalCompilation/Bitcode/BitstreamVisitor.swift
1
1064
//===----------- BitstreamVisitor.swift - LLVM Bitstream Visitor ----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// public protocol BitstreamVisitor { /// Customization point to validate a bitstream's signature or "magic number". func validate(signature: Bitcode.Signature) throws /// Called when a new block is encountered. Return `true` to enter the block /// and read its contents, or `false` to skip it. mutating func shouldEnterBlock(id: UInt64) throws -> Bool /// Called when a block is exited. mutating func didExitBlock() throws /// Called whenever a record is encountered. mutating func visit(record: BitcodeElement.Record) throws }
apache-2.0
evgeny-emelyanov/if-park-safe
ParkSafe/SecondViewController.swift
1
8452
// // SecondViewController.swift // ParkSafe // // Created by Katerina on 11/20/16. // Copyright © 2016 IF. All rights reserved. // import UIKit import GoogleMaps class SecondViewController: UIViewController, CLLocationManagerDelegate { var safetyPoints = 0 var notificationManager: NotificationManager? var locationManager: CLLocationManager? var mapView: GMSMapView? var oldLocation: CLLocation? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if notificationManager == nil{ notificationManager = (UIApplication.shared.delegate as! AppDelegate).notificationManager } if locationManager == nil { locationManager = getLocationManager() } let camera = GMSCameraPosition.camera(withLatitude: 56.9516026, longitude: 24.119115, zoom: 12) mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera) mapView?.isMyLocationEnabled = true; self.view = mapView addAlfa(mapView: mapView!) addMarupe(mapView: mapView!) addSpice(mapView: mapView!) } func getLocationManager() -> CLLocationManager { let manager = CLLocationManager() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest manager.requestAlwaysAuthorization() manager.startUpdatingLocation() return manager } func addMarupe(mapView: GMSMapView) { let path = GMSMutablePath() path.add(CLLocationCoordinate2DMake(56.904067, 23.993930)) path.add(CLLocationCoordinate2DMake(56.915782, 23.981742)) path.add(CLLocationCoordinate2DMake(56.927400, 23.997535)) path.add(CLLocationCoordinate2DMake(56.926557, 24.038905)) path.add(CLLocationCoordinate2DMake(56.912216, 24.044989)) path.add(CLLocationCoordinate2DMake(56.905848, 24.081306)) path.add(CLLocationCoordinate2DMake(56.892911, 24.074611)) path.add(CLLocationCoordinate2DMake(56.881002, 24.037189)) path.add(CLLocationCoordinate2DMake(56.887660, 24.032897)) path.add(CLLocationCoordinate2DMake(56.885785, 24.010581)) path.add(CLLocationCoordinate2DMake(56.889629, 24.008693)) path.add(CLLocationCoordinate2DMake(56.897505, 24.033927)) path.add(CLLocationCoordinate2DMake(56.908285, 24.022597)) path.add(CLLocationCoordinate2DMake(56.904067, 23.993930)) let rectangle = GMSPolyline(path: path) rectangle.strokeWidth = 2 let solidRed = GMSStrokeStyle.solidColor(UIColor.red) rectangle.spans = [GMSStyleSpan(style: solidRed)] rectangle.map = mapView } func addAlfa(mapView: GMSMapView){ let path = GMSMutablePath() path.add(CLLocationCoordinate2DMake(56.982832, 24.201361)) path.add(CLLocationCoordinate2DMake(56.983393, 24.200846)) path.add(CLLocationCoordinate2DMake(56.984404, 24.205030)) path.add(CLLocationCoordinate2DMake(56.982935, 24.206042)) path.add(CLLocationCoordinate2DMake(56.982836, 24.205141)) path.add(CLLocationCoordinate2DMake(56.983666, 24.204358)) path.add(CLLocationCoordinate2DMake(56.982832, 24.201361)) let rectangle = GMSPolyline(path: path) rectangle.strokeWidth = 2 let solidRed = GMSStrokeStyle.solidColor(UIColor.red) rectangle.spans = [GMSStyleSpan(style: solidRed)] rectangle.map = mapView } func addSpice(mapView: GMSMapView){ var path = GMSMutablePath() let solidRed = GMSStrokeStyle.solidColor(UIColor.red) path.add(CLLocationCoordinate2DMake(56.929469, 24.033065)) path.add(CLLocationCoordinate2DMake(56.930897, 24.035565)) path.add(CLLocationCoordinate2DMake(56.930452, 24.036402)) path.add(CLLocationCoordinate2DMake(56.929351, 24.034181)) path.add(CLLocationCoordinate2DMake(56.929469, 24.033065)) var rectangle = GMSPolyline(path: path) rectangle.strokeWidth = 2 rectangle.spans = [GMSStyleSpan(style: solidRed)] rectangle.map = mapView path = GMSMutablePath() path.add(CLLocationCoordinate2DMake(56.930258, 24.037121)) path.add(CLLocationCoordinate2DMake(56.930849, 24.038301)) path.add(CLLocationCoordinate2DMake(56.930217, 24.039395)) path.add(CLLocationCoordinate2DMake(56.929392, 24.039009)) path.add(CLLocationCoordinate2DMake(56.930258, 24.037121)) rectangle = GMSPolyline(path: path) rectangle.strokeWidth = 2 rectangle.spans = [GMSStyleSpan(style: solidRed)] rectangle.map = mapView notificationManager?.scheduleNotification(identifier: "Spice", title: "High risk of vandalism near Spice!", subtitle: "", body: "Dear Jānis, please keep an eye on your Volvo XC90 in Spice parking area! Headlights of Volvo has been stolen 5 times in 3 months here. Do you know a single headlight unit for your car costs about 3000 EUR? This makes your car a top choice for thefts. Do not leave it unattended here.", latitude: 56.930258, longitude: 24.037121, radius: 100, areaIdentifier: "Spice", repeats: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func goToArea1(_ sender: UIButton) { } func startUpdatingLocation() { self.locationManager?.startUpdatingLocation() } func stopUpdatingLocation() { self.locationManager?.stopUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let defaults = UserDefaults() let latestLocation = locations.last if oldLocation != nil { if let distanceToOldLocation = latestLocation?.distance(from: oldLocation!) { if (distanceToOldLocation > 10 ) { let camera = GMSCameraPosition.camera(withLatitude: (latestLocation?.coordinate.latitude)!, longitude:(latestLocation?.coordinate.longitude)!, zoom:14) self.mapView?.animate(to: camera) } } } else { let camera = GMSCameraPosition.camera(withLatitude: (latestLocation?.coordinate.latitude)!, longitude:(latestLocation?.coordinate.longitude)!, zoom:14) self.mapView?.animate(to: camera) } oldLocation = latestLocation let spiceLocation = CLLocation(latitude: 56.930258, longitude: 24.037121) let marupeLocation = CLLocation(latitude: 56.916645, longitude: 24.011521) let alfaLocation = CLLocation(latitude: 56.982832, longitude: 24.201361) let spiceDistance = latestLocation?.distance(from: spiceLocation) let marupeDistance = latestLocation?.distance(from: marupeLocation) let alfaDistance = latestLocation?.distance(from: alfaLocation) let inSpice = Double(spiceDistance ?? 0) < 100.00 let inMarupe = Double(marupeDistance ?? 0) < 100.00 let inAlfa = Double(alfaDistance ?? 0) < 100.00 //print("distance not determined: \(distance == nil)") //print("distance: \(distance)") let currentPoints = defaults.integer(forKey: "safetyPoints") if inSpice || inMarupe || inAlfa { if (Int(currentPoints) > 0) { defaults.set(currentPoints - 1, forKey: "safetyPoints") } } else { defaults.set(currentPoints + 1, forKey: "safetyPoints") } print("sp: \(defaults.integer(forKey: "safetyPoints"))") let latitude = String(format: "%.4f", latestLocation!.coordinate.latitude) let longitude = String(format: "%.4f", latestLocation!.coordinate.longitude) print("Lat: \(latitude), Long: \(longitude)") } }
apache-2.0
PJayRushton/stats
Stats/NSAttributedString+Helpers.swift
1
1902
/* | _ ____ ____ _ | | |‾| ⚈ |-| ⚈ |‾| | | | | ‾‾‾‾| |‾‾‾‾ | | | ‾ ‾ ‾ */ import Foundation import UIKit public extension NSMutableAttributedString { public func increaseFontSize(by multiplier: CGFloat) { enumerateAttribute(NSAttributedStringKey.font, in: NSMakeRange(0, length), options: []) { (font, range, stop) in guard let font = font as? UIFont else { return } let newFont = font.withSize(font.pointSize * multiplier) removeAttribute(NSAttributedStringKey.font, range: range) addAttribute(NSAttributedStringKey.backgroundColor, value: newFont, range: range) } } func highlightStrings(_ stringToHighlight: String?, color: UIColor) { let textMatches = string.matches(for: stringToHighlight) for match in textMatches { addAttribute(NSAttributedStringKey.backgroundColor, value: color, range: match.range) } } } public extension String { func matches(for stringToHighlight: String?) -> [NSTextCheckingResult] { guard let stringToHighlight = stringToHighlight, !stringToHighlight.isEmpty else { return [] } do { let expression = try NSRegularExpression(pattern: stringToHighlight, options: [.caseInsensitive, .ignoreMetacharacters]) return expression.matches(in: self, options: [], range: NSRange(location: 0, length: count)) } catch { print("status=could-not-create-regex error=\(error)") return [] } } } public extension NSAttributedString { public func withIncreasedFontSize(by multiplier: CGFloat) -> NSAttributedString { let mutableCopy = NSMutableAttributedString(attributedString: self) mutableCopy.increaseFontSize(by: multiplier) return mutableCopy } }
mit
blockchain/My-Wallet-V3-iOS
Blockchain/Models/Direction.swift
1
140
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation @objc enum Direction: Int { case up case down }
lgpl-3.0
eofster/Telephone
UseCasesTestDoubles/ContactMatchingStub.swift
1
977
// // ContactMatchingStub.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2021 64 Characters // // Telephone 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. // // Telephone 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. // import UseCases public final class ContactMatchingStub { let matches: [URI: MatchedContact] public init(_ matches: [URI: MatchedContact]) { self.matches = matches } } extension ContactMatchingStub: ContactMatching { public func match(for uri: URI) -> MatchedContact? { return matches[uri] } }
gpl-3.0
timfuqua/Bourgeoisie
Bourgeoisie/BourgeoisieTests/CardDeckTests.swift
1
17076
// // CardDeckTests.swift // Bourgeoisie // // Created by Tim Fuqua on 1/2/16. // Copyright © 2016 FuquaProductions. All rights reserved. // import XCTest import Buckets @testable import Bourgeoisie class CardDeckTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: Test init func testInitEmpty() { let deck = BourgDeck() XCTAssert(deck.numberOfCards == 0) deck.printDeckTopToBottom() } func testInitHearts() { let deck = BourgDeck(cards: SPC.allHearts) deck.printDeckTopToBottom() XCTAssert(deck.numberOfCards == 13) XCTAssert(deck.dequeCards.filter({ return $0.suit == Suit.Hearts }).count == 13) } func testInitDiamonds() { let deck = BourgDeck(cards: SPC.allDiamonds) deck.printDeckTopToBottom() XCTAssert(deck.numberOfCards == 13) XCTAssert(deck.dequeCards.filter({ return $0.suit == Suit.Diamonds }).count == 13) deck.printDeckTopToBottom() } func testInitSpades() { let deck = BourgDeck(cards: SPC.allSpades) deck.printDeckTopToBottom() XCTAssert(deck.numberOfCards == 13) XCTAssert(deck.dequeCards.filter({ return $0.suit == Suit.Spades }).count == 13) deck.printDeckTopToBottom() } func testInitClubs() { let deck = BourgDeck(cards: SPC.allClubs) deck.printDeckTopToBottom() XCTAssert(deck.numberOfCards == 13) XCTAssert(deck.dequeCards.filter({ return $0.suit == Suit.Clubs }).count == 13) deck.printDeckTopToBottom() } // MARK: Test has cards func testHasCard() { let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs] let acesDeck = BourgDeck(cards: aces) XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() } func testNumberOfCopiesOfCard() { let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs] let acesDeck = BourgDeck(cards: aces) XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.addCardToTop(SPC.aceOfHearts) XCTAssert(acesDeck.numberOfCards == 5) XCTAssert(acesDeck.numberOfCopiesOfCard(SPC.aceOfHearts) == 2) XCTAssert(acesDeck.hasCard(SPC.twoOfHearts) == false) XCTAssert(acesDeck.numberOfCopiesOfCard(SPC.twoOfHearts) == 0) acesDeck.printDeckTopToBottom() } // MARK: Test add cards func testAddCardToTop() { let initiallyEmptyDeck = BourgDeck() initiallyEmptyDeck.addCardToTop(SPC.aceOfHearts) XCTAssert(initiallyEmptyDeck.numberOfCards == 1) XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfHearts)) initiallyEmptyDeck.printDeckTopToBottom() initiallyEmptyDeck.addCardToTop(SPC.aceOfDiamonds) initiallyEmptyDeck.addCardToTop(SPC.aceOfSpades) initiallyEmptyDeck.addCardToTop(SPC.aceOfClubs) XCTAssert(initiallyEmptyDeck.numberOfCards == 4) XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfHearts) && initiallyEmptyDeck.arrayCards[0] == SPC.aceOfHearts) XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfDiamonds) && initiallyEmptyDeck.arrayCards[1] == SPC.aceOfDiamonds) XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfSpades) && initiallyEmptyDeck.arrayCards[2] == SPC.aceOfSpades) XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfClubs) && initiallyEmptyDeck.arrayCards[3] == SPC.aceOfClubs) initiallyEmptyDeck.printDeckTopToBottom() } func testAddCardToBottom() { let initiallyEmptyDeck = BourgDeck() initiallyEmptyDeck.addCardToBottom(SPC.aceOfHearts) XCTAssert(initiallyEmptyDeck.numberOfCards == 1) XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfHearts)) initiallyEmptyDeck.printDeckTopToBottom() initiallyEmptyDeck.addCardToBottom(SPC.aceOfDiamonds) initiallyEmptyDeck.addCardToBottom(SPC.aceOfSpades) initiallyEmptyDeck.addCardToBottom(SPC.aceOfClubs) XCTAssert(initiallyEmptyDeck.numberOfCards == 4) XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfHearts) && initiallyEmptyDeck.arrayCards[3] == SPC.aceOfHearts) XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfDiamonds) && initiallyEmptyDeck.arrayCards[2] == SPC.aceOfDiamonds) XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfSpades) && initiallyEmptyDeck.arrayCards[1] == SPC.aceOfSpades) XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfClubs) && initiallyEmptyDeck.arrayCards[0] == SPC.aceOfClubs) initiallyEmptyDeck.printDeckTopToBottom() } // MARK: Test remove cards func testRemoveCardFromTop() { let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs] let acesDeck = BourgDeck(cards: aces) XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() acesDeck.removeCardFromTop() XCTAssert(acesDeck.numberOfCards == 3) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts) == false) acesDeck.printDeckTopToBottom() acesDeck.removeCardFromTop() XCTAssert(acesDeck.numberOfCards == 2) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds) == false) acesDeck.printDeckTopToBottom() acesDeck.removeCardFromTop() XCTAssert(acesDeck.numberOfCards == 1) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades) == false) acesDeck.printDeckTopToBottom() acesDeck.removeCardFromTop() XCTAssert(acesDeck.numberOfCards == 0) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs) == false) acesDeck.printDeckTopToBottom() } func testRemoveCardFromBottom() { let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs] let acesDeck = BourgDeck(cards: aces) XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() acesDeck.removeCardFromBottom() XCTAssert(acesDeck.numberOfCards == 3) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs) == false) acesDeck.printDeckTopToBottom() acesDeck.removeCardFromBottom() XCTAssert(acesDeck.numberOfCards == 2) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades) == false) acesDeck.printDeckTopToBottom() acesDeck.removeCardFromBottom() XCTAssert(acesDeck.numberOfCards == 1) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds) == false) acesDeck.printDeckTopToBottom() acesDeck.removeCardFromBottom() XCTAssert(acesDeck.numberOfCards == 0) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts) == false) acesDeck.printDeckTopToBottom() } func testRemoveFirstOccurenceOfCard() { let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs] let acesDeck = BourgDeck(cards: aces) XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() acesDeck.addCardToBottom(SPC.aceOfHearts) XCTAssert(acesDeck.numberOfCopiesOfCard(SPC.aceOfHearts) == 2) acesDeck.printDeckTopToBottom() acesDeck.removeFirstOccurenceOfCard(SPC.aceOfHearts) XCTAssert(acesDeck.numberOfCopiesOfCard(SPC.aceOfHearts) == 1) acesDeck.printDeckTopToBottom() } func testRemoveAllCards() { let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs] let acesDeck = BourgDeck(cards: aces) XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() acesDeck.removeAllCards() XCTAssert(acesDeck.numberOfCards == 0) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts) == false) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds) == false) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades) == false) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs) == false) acesDeck.printDeckTopToBottom() } // MARK: Test shuffle func testShuffle() { let originalHeartsDeck = BourgDeck(cards: SPC.allHearts) let shuffledHeartsDeck = BourgDeck(cards: SPC.allHearts) XCTAssert(originalHeartsDeck.numberOfCards == 13) XCTAssert(shuffledHeartsDeck.numberOfCards == 13) originalHeartsDeck.printDeckTopToBottom() shuffledHeartsDeck.shuffle() shuffledHeartsDeck.printDeckTopToBottom() XCTAssert(originalHeartsDeck != shuffledHeartsDeck) } // MARK: Test peek func testPeekAtTopCard() { let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs] let acesDeck = BourgDeck(cards: aces) XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() print(acesDeck.peekAtTopCard() ?? "Empty Deck") XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() } func testPeekAtCardOffsetFromTop() { let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs] let acesDeck = BourgDeck(cards: aces) XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() print("Peeking 1 deep: ", terminator: "") print(acesDeck.peekAtCardOffsetFromTop(1) ?? "Empty Deck or peeking beyond bottom of deck") print("Peeking 2 deep: ", terminator: "") print(acesDeck.peekAtCardOffsetFromTop(2) ?? "Empty Deck or peeking beyond bottom of deck") print("Peeking 3 deep: ", terminator: "") print(acesDeck.peekAtCardOffsetFromTop(3) ?? "Empty Deck or peeking beyond bottom of deck") print("Peeking 4 deep: ", terminator: "") print(acesDeck.peekAtCardOffsetFromTop(4) ?? "Empty Deck or peeking beyond bottom of deck") print("Peeking 5 deep: ", terminator: "") print(acesDeck.peekAtCardOffsetFromTop(5) ?? "Empty Deck or peeking beyond bottom of deck") XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() } // MARK: Test draw cards func testDrawTopCard() { let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs] let acesDeck = BourgDeck(cards: aces) XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() print("Drawing top card: ", terminator: "") print(acesDeck.drawTopCard() ?? "Empty Deck") XCTAssert(acesDeck.numberOfCards == 3) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts) == false) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() print("Drawing top card: ", terminator: "") print(acesDeck.drawTopCard() ?? "Empty Deck") acesDeck.printDeckTopToBottom() print("Drawing top card: ", terminator: "") print(acesDeck.drawTopCard() ?? "Empty Deck") acesDeck.printDeckTopToBottom() print("Drawing top card: ", terminator: "") print(acesDeck.drawTopCard() ?? "Empty Deck") acesDeck.printDeckTopToBottom() print("Drawing top card: ", terminator: "") print(acesDeck.drawTopCard() ?? "Empty Deck") } func testDrawTopCards() { let acesDeck = BourgDeck(cards: SPC.allAces) XCTAssert(acesDeck.numberOfCards == 4) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts)) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds)) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades)) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs)) acesDeck.printDeckTopToBottom() print("Drawing top 2 cards: ", terminator: "") print(acesDeck.drawTopCards(2) ?? "Empty Deck") XCTAssert(acesDeck.numberOfCards == 2) XCTAssert(acesDeck.hasCard(SPC.aceOfHearts) == false) XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds) == false) XCTAssert(acesDeck.hasCard(SPC.aceOfSpades) == true) XCTAssert(acesDeck.hasCard(SPC.aceOfClubs) == true) acesDeck.printDeckTopToBottom() print("Drawing top 3 cards: ", terminator: "") print(acesDeck.drawTopCards(3) ?? "Empty Deck") acesDeck.printDeckTopToBottom() print("Drawing top card: ", terminator: "") print(acesDeck.drawTopCard() ?? "Empty Deck") } // MARK: Test move cards func testMoveTopCards() { let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs] let originalDeck = BourgDeck(cards: aces) let deck = BourgDeck(cards: aces) let discardPile = BourgDeck() XCTAssert(deck.numberOfCards == 4) XCTAssert(deck.hasCard(SPC.aceOfHearts)) XCTAssert(deck.hasCard(SPC.aceOfDiamonds)) XCTAssert(deck.hasCard(SPC.aceOfSpades)) XCTAssert(deck.hasCard(SPC.aceOfClubs)) XCTAssert(discardPile.numberOfCards == 0) print("\"Deck\" ", terminator: "") deck.printDeckTopToBottom() print("\"Discard Pile\" ", terminator: "") discardPile.printDeckTopToBottom() print("Attempt to move top 5 cards") deck.moveTopCards(5, toDeck: discardPile) XCTAssert(deck.numberOfCards == 4) XCTAssert(deck.hasCard(SPC.aceOfHearts)) XCTAssert(deck.hasCard(SPC.aceOfDiamonds)) XCTAssert(deck.hasCard(SPC.aceOfSpades)) XCTAssert(deck.hasCard(SPC.aceOfClubs)) XCTAssert(discardPile.numberOfCards == 0) print("\"Deck\" ", terminator: "") deck.printDeckTopToBottom() print("\"Discard Pile\" ", terminator: "") discardPile.printDeckTopToBottom() print("Attempt to move top 1 cards") deck.moveTopCards(1, toDeck: discardPile) XCTAssert(deck.numberOfCards == 3) XCTAssert(deck.hasCard(SPC.aceOfHearts) == false) XCTAssert(deck.hasCard(SPC.aceOfDiamonds)) XCTAssert(deck.hasCard(SPC.aceOfSpades)) XCTAssert(deck.hasCard(SPC.aceOfClubs)) XCTAssert(discardPile.numberOfCards == 1) XCTAssert(discardPile.hasCard(SPC.aceOfHearts)) print("\"Deck\" ", terminator: "") deck.printDeckTopToBottom() print("\"Discard Pile\" ", terminator: "") discardPile.printDeckTopToBottom() print("Attempt to move top 3 cards") deck.moveTopCards(3, toDeck: discardPile) XCTAssert(deck.numberOfCards == 0) XCTAssert(deck.hasCard(SPC.aceOfHearts) == false) XCTAssert(deck.hasCard(SPC.aceOfDiamonds) == false) XCTAssert(deck.hasCard(SPC.aceOfSpades) == false) XCTAssert(deck.hasCard(SPC.aceOfClubs) == false) XCTAssert(discardPile.numberOfCards == 4) XCTAssert(discardPile.hasCard(SPC.aceOfHearts)) XCTAssert(discardPile.hasCard(SPC.aceOfDiamonds)) XCTAssert(discardPile.hasCard(SPC.aceOfSpades)) XCTAssert(discardPile.hasCard(SPC.aceOfClubs)) print("\"Deck\" ", terminator: "") deck.printDeckTopToBottom() print("\"Discard Pile\" ", terminator: "") discardPile.printDeckTopToBottom() XCTAssert(discardPile.arrayCards.reverse() == originalDeck.arrayCards) } }
mit
GianniCarlo/JSQMessagesViewController
SwiftExample/SwiftExample/ChatViewController.swift
1
26320
// // ChatViewController.swift // SwiftExample // // Created by Dan Leonard on 5/11/16. // Copyright © 2016 MacMeDan. All rights reserved. // import UIKit import JSQMessagesViewController protocol JSQDemoViewControllerDelegate : NSObjectProtocol { func didDismissJSQDemoViewController(vc: ChatViewController) } /** * Override point for customization. * * Customize your view. * Look at the properties on `JSQMessagesViewController` and `JSQMessagesCollectionView` to see what is possible. * * Customize your layout. * Look at the properties on `JSQMessagesCollectionViewFlowLayout` to see what is possible. */ class ChatViewController: JSQMessagesViewController, JSQMessagesComposerTextViewPasteDelegate { var conversation: Conversation! var outgoingBubbleImageData: JSQMessagesBubbleImage! var incomingBubbleImageData: JSQMessagesBubbleImage! weak var delegateModal: JSQDemoViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() self.title = self.conversation.name; /** * You MUST set your senderId and display name */ self.senderId = AvatarIDCarlo; self.senderDisplayName = DisplayNameCarlo; self.inputToolbar.contentView.textView.pasteDelegate = self; /** * You can set custom avatar sizes */ // self.collectionView.collectionViewLayout.incomingAvatarViewSize = .zero; // self.collectionView.collectionViewLayout.outgoingAvatarViewSize = .zero; self.showLoadEarlierMessagesHeader = true; self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.jsq_defaultTypingIndicatorImage(), style: .Plain, target: self, action: #selector(receiveMessagePressed)) /** * Register custom menu actions for cells. */ JSQMessagesCollectionViewCell.registerMenuAction(#selector(customAction)) /** * OPT-IN: allow cells to be deleted */ JSQMessagesCollectionViewCell.registerMenuAction(#selector(delete(_:))) /** * Customize your toolbar buttons * * self.inputToolbar.contentView.leftBarButtonItem = custom button or nil to remove * self.inputToolbar.contentView.rightBarButtonItem = custom button or nil to remove */ /** * Set a maximum height for the input toolbar * * self.inputToolbar.maximumHeight = 150.0 */ /** * Enable/disable springy bubbles, default is NO. * You must set this from `viewDidAppear:` * Note: this feature is mostly stable, but still experimental * * self.collectionView.collectionViewLayout.springinessEnabled = true */ /** * Create message bubble images objects. * * Be sure to create your bubble images one time and reuse them for good performance. * */ let bubbleFactory = JSQMessagesBubbleImageFactory() self.outgoingBubbleImageData = bubbleFactory.outgoingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleLightGrayColor()) self.incomingBubbleImageData = bubbleFactory.incomingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleGreenColor()) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if (self.delegateModal) != nil { self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: #selector(closePressed)) } } /** * Get random user except me */ func getRandomRecipient() -> User { let members = self.conversation.members.filter({ $0.id != self.senderId }) let user = members[Int(arc4random_uniform(UInt32(members.count)))] return user } //MARK: Custom menu actions for cells override func didReceiveMenuWillShowNotification(notification: NSNotification!) { /** * Display custom menu actions for cells. */ let menu = notification.object as! UIMenuController menu.menuItems = [UIMenuItem(title: "Custom Action", action: #selector(self.customAction(_:)))] } //MARK: Actions func receiveMessagePressed(sender: UIBarButtonItem) { /** * DEMO ONLY * * The following is simply to simulate received messages for the demo. * Do not actually do this. */ /** * Show the typing indicator to be shown */ self.showTypingIndicator = !self.showTypingIndicator /** * Scroll to actually view the indicator */ self.scrollToBottomAnimated(true) /** * Get random user that isn't me */ let user = self.getRandomRecipient() /** * Copy last sent message, this will be the new "received" message */ var copyMessage = self.conversation.messages.last?.copy() if (copyMessage == nil) { copyMessage = JSQMessage(senderId: user.id, displayName: user.name, text: "First received!") } /** * Allow typing indicator to show */ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { var newMessage:JSQMessage? var newMediaData:JSQMessageMediaData? var newMediaAttachmentCopy:AnyObject? if copyMessage!.isMediaMessage() { /** * Last message was a media message */ let copyMediaData = copyMessage!.media switch copyMediaData { case is JSQPhotoMediaItem: let photoItemCopy = (copyMediaData as! JSQPhotoMediaItem).copy() as! JSQPhotoMediaItem photoItemCopy.appliesMediaViewMaskAsOutgoing = false newMediaAttachmentCopy = UIImage(CGImage: photoItemCopy.image.CGImage!) /** * Set image to nil to simulate "downloading" the image * and show the placeholder view */ photoItemCopy.image = nil; newMediaData = photoItemCopy case is JSQLocationMediaItem: let locationItemCopy = (copyMediaData as! JSQLocationMediaItem).copy() as! JSQLocationMediaItem locationItemCopy.appliesMediaViewMaskAsOutgoing = false newMediaAttachmentCopy = locationItemCopy.location.copy() /** * Set location to nil to simulate "downloading" the location data */ locationItemCopy.location = nil; newMediaData = locationItemCopy; case is JSQVideoMediaItem: let videoItemCopy = (copyMediaData as! JSQVideoMediaItem).copy() as! JSQVideoMediaItem videoItemCopy.appliesMediaViewMaskAsOutgoing = false newMediaAttachmentCopy = videoItemCopy.fileURL.copy() /** * Reset video item to simulate "downloading" the video */ videoItemCopy.fileURL = nil; videoItemCopy.isReadyToPlay = false; newMediaData = videoItemCopy; case is JSQAudioMediaItem: let audioItemCopy = (copyMediaData as! JSQAudioMediaItem).copy() as! JSQAudioMediaItem audioItemCopy.appliesMediaViewMaskAsOutgoing = false newMediaAttachmentCopy = audioItemCopy.audioData?.copy() /** * Reset audio item to simulate "downloading" the audio */ audioItemCopy.audioData = nil; newMediaData = audioItemCopy; default: print("error: unrecognized media item") } newMessage = JSQMessage(senderId: user.id, displayName: user.name, media: newMediaData) } else { /** * Last message was a text message */ newMessage = JSQMessage(senderId: user.id, displayName: user.name, text: copyMessage!.text) } /** * Upon receiving a message, you should: * * 1. Play sound (optional) * 2. Add new JSQMessageData object to your data source * 3. Call `finishReceivingMessage` */ JSQSystemSoundPlayer.jsq_playMessageReceivedSound() self.conversation.messages.append(newMessage!) self.finishReceivingMessageAnimated(true) if newMessage!.isMediaMessage { /** * Simulate "downloading" media */ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { /** * Media is "finished downloading", re-display visible cells * * If media cell is not visible, the next time it is dequeued the view controller will display its new attachment data * * Reload the specific item, or simply call `reloadData` */ switch newMediaData { case is JSQPhotoMediaItem: (newMediaData as! JSQPhotoMediaItem).image = newMediaAttachmentCopy as! UIImage self.collectionView.reloadData() case is JSQLocationMediaItem: (newMediaData as! JSQLocationMediaItem).setLocation(newMediaAttachmentCopy as! CLLocation, withCompletionHandler: { self.collectionView.reloadData() }) case is JSQVideoMediaItem: (newMediaData as! JSQVideoMediaItem).fileURL = newMediaAttachmentCopy as! NSURL (newMediaData as! JSQVideoMediaItem).isReadyToPlay = true self.collectionView.reloadData() case is JSQAudioMediaItem: (newMediaData as! JSQAudioMediaItem).audioData = newMediaAttachmentCopy as? NSData self.collectionView.reloadData() default: print("error: unrecognized media item") } } } } } func closePressed(sender:UIBarButtonItem) { self.delegateModal?.didDismissJSQDemoViewController(self) } // MARK: JSQMessagesViewController method overrides override func didPressSendButton(button: UIButton?, withMessageText text: String?, senderId: String?, senderDisplayName: String?, date: NSDate?) { /** * Sending a message. Your implementation of this method should do *at least* the following: * * 1. Play sound (optional) * 2. Add new id<JSQMessageData> object to your data source * 3. Call `finishSendingMessage` */ JSQSystemSoundPlayer.jsq_playMessageSentSound() let message = JSQMessage(senderId: senderId, senderDisplayName: senderDisplayName, date: date, text: text) self.conversation.messages.append(message) self.finishSendingMessageAnimated(true) } override func didPressAccessoryButton(sender: UIButton!) { self.inputToolbar.contentView.textView.resignFirstResponder() let sheet = UIAlertController(title: "Media messages", message: nil, preferredStyle: .ActionSheet) let photoButton = UIAlertAction(title: "Send photo", style: .Default) { (action) in /** * Add fake photo into conversation messages */ let photoItem = JSQPhotoMediaItem(image: UIImage(named: "goldengate")) let photoMessage = JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: photoItem) self.conversation.messages.append(photoMessage) JSQSystemSoundPlayer.jsq_playMessageSentSound() self.finishSendingMessageAnimated(true) } let locationButton = UIAlertAction(title: "Send location", style: .Default) { (action) in /** * Add fake location into conversation messages */ let ferryBuildingInSF = CLLocation(latitude: 37.795313, longitude: -122.393757) let locationItem = JSQLocationMediaItem() locationItem.setLocation(ferryBuildingInSF) { self.collectionView.reloadData() } let locationMessage = JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: locationItem) self.conversation.messages.append(locationMessage) JSQSystemSoundPlayer.jsq_playMessageSentSound() self.finishSendingMessageAnimated(true) } let videoButton = UIAlertAction(title: "Send video", style: .Default) { (action) in /** * Add fake video into conversation messages */ let videoURL = NSURL(fileURLWithPath: "file://") let videoItem = JSQVideoMediaItem(fileURL: videoURL, isReadyToPlay: true) let videoMessage = JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: videoItem) self.conversation.messages.append(videoMessage) JSQSystemSoundPlayer.jsq_playMessageSentSound() self.finishSendingMessageAnimated(true) } let audioButton = UIAlertAction(title: "Send audio", style: .Default) { (action) in /** * Add fake audio into conversation messages */ let sample = NSBundle.mainBundle().pathForResource("jsq_messages_sample", ofType: "m4a") let audioData = NSData(contentsOfFile: sample!) let audioItem = JSQAudioMediaItem(data: audioData) let audioMessage = JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: audioItem) self.conversation.messages.append(audioMessage) JSQSystemSoundPlayer.jsq_playMessageSentSound() self.finishSendingMessageAnimated(true) } let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) sheet.addAction(photoButton) sheet.addAction(locationButton) sheet.addAction(videoButton) sheet.addAction(audioButton) sheet.addAction(cancelButton) self.presentViewController(sheet, animated: true, completion: nil) } // MARK: JSQMessages CollectionView DataSource override func collectionView(collectionView: JSQMessagesCollectionView?, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData? { return self.conversation.messages[indexPath.item] } override func collectionView(collectionView: JSQMessagesCollectionView!, didDeleteMessageAtIndexPath indexPath: NSIndexPath!) { self.conversation.messages.removeAtIndex(indexPath.item) } override func collectionView(collectionView: JSQMessagesCollectionView?, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource? { /** * You may return nil here if you do not want bubbles. * In this case, you should set the background color of your collection view cell's textView. * * Otherwise, return your previously created bubble image data objects. */ let message = self.conversation.messages[indexPath.item] if message.senderId == self.senderId { return self.outgoingBubbleImageData } return self.incomingBubbleImageData; } override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource? { /** * Return `nil` here if you do not want avatars. * If you do return `nil`, be sure to do the following in `viewDidLoad`: * * self.collectionView.collectionViewLayout.incomingAvatarViewSize = .zero; * self.collectionView.collectionViewLayout.outgoingAvatarViewSize = .zero; * * It is possible to have only outgoing avatars or only incoming avatars, too. */ /** * Return your previously created avatar image data objects. * * Note: these the avatars will be sized according to these values: * * self.collectionView.collectionViewLayout.incomingAvatarViewSize * self.collectionView.collectionViewLayout.outgoingAvatarViewSize * * Override the defaults in `viewDidLoad` */ let message = self.conversation.messages[indexPath.item] guard let user = self.conversation.getUser(message.senderId) else{ return nil } return user.avatar } override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! { /** * This logic should be consistent with what you return from `heightForCellTopLabelAtIndexPath:` * The other label text delegate methods should follow a similar pattern. * * Show a timestamp for every 3rd message */ if (indexPath.item % 3) == 0 { let message = self.conversation.messages[indexPath.item] return JSQMessagesTimestampFormatter.sharedFormatter().attributedTimestampForDate(message.date) } return nil; } override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! { let message = self.conversation.messages[indexPath.item] /** * iOS7-style sender name labels */ if message.senderId == self.senderId { return nil; } if (indexPath.item - 1) > 0 { let previousMessage = self.conversation.messages[indexPath.item - 1] if previousMessage.senderId == message.senderId { return nil; } } /** * Don't specify attributes to use the defaults. */ return NSAttributedString(string: message.senderDisplayName) } override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! { return nil } // MARK: UICollectionView DataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.conversation.messages.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { /** * Override point for customizing cells */ let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell /** * Configure almost *anything* on the cell * * Text colors, label text, label colors, etc. * * * DO NOT set `cell.textView.font` ! * Instead, you need to set `self.collectionView.collectionViewLayout.messageBubbleFont` to the font you want in `viewDidLoad` * * * DO NOT manipulate cell layout information! * Instead, override the properties you want on `self.collectionView.collectionViewLayout` from `viewDidLoad` */ let msg = self.conversation.messages[indexPath.item] if !msg.isMediaMessage { if msg.senderId == self.senderId { cell.textView.textColor = UIColor.blackColor() } else { cell.textView.textColor = UIColor.whiteColor() } let attributes : [String:AnyObject] = [NSForegroundColorAttributeName:cell.textView.textColor!, NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue] cell.textView.linkTextAttributes = attributes } return cell; } // MARK: UICollectionView Delegate // MARK: Custom menu items override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { if action == #selector(customAction) { return true } return super.collectionView(collectionView, canPerformAction: action, forItemAtIndexPath: indexPath, withSender: sender) } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { if action == Selector() { self.customAction(sender!) return } super.collectionView(collectionView, performAction: action, forItemAtIndexPath: indexPath, withSender: sender) } func customAction(sender: AnyObject) { print("Custom action received! Sender: \(sender)") } // MARK: JSQMessages collection view flow layout delegate // MARK: Adjusting cell label heights override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat { /** * Each label in a cell has a `height` delegate method that corresponds to its text dataSource method */ /** * This logic should be consistent with what you return from `attributedTextForCellTopLabelAtIndexPath:` * The other label height delegate methods should follow similarly * * Show a timestamp for every 3rd message */ if (indexPath.item % 3) == 0 { return kJSQMessagesCollectionViewCellLabelHeightDefault } return 0.0 } override func collectionView(collectionView: JSQMessagesCollectionView?, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout?, heightForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat { /** * iOS7-style sender name labels */ let currentMessage = self.conversation.messages[indexPath.item] if currentMessage.senderId == self.senderId { return 0.0 } if (indexPath.item - 1) > 0 { let previousMessage = self.conversation.messages[indexPath.item - 1] if previousMessage.senderId == currentMessage.senderId { return 0.0 } } return kJSQMessagesCollectionViewCellLabelHeightDefault; } override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat { return 0.0 } // MARK: Responding to collection view tap events override func collectionView(collectionView: JSQMessagesCollectionView!, header headerView: JSQMessagesLoadEarlierHeaderView!, didTapLoadEarlierMessagesButton sender: UIButton!) { print("Load earlier messages!") } override func collectionView(collectionView: JSQMessagesCollectionView!, didTapAvatarImageView avatarImageView: UIImageView!, atIndexPath indexPath: NSIndexPath!) { print("Tapped avatar!") } override func collectionView(collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAtIndexPath indexPath: NSIndexPath!) { print("Tapped message bubble!") } override func collectionView(collectionView: JSQMessagesCollectionView!, didTapCellAtIndexPath indexPath: NSIndexPath!, touchLocation: CGPoint) { print("Tapped cell at \(touchLocation)") } // MARK: JSQMessagesComposerTextViewPasteDelegate methods func composerTextView(textView: JSQMessagesComposerTextView!, shouldPasteWithSender sender: AnyObject!) -> Bool { if (UIPasteboard.generalPasteboard().image != nil) { // If there's an image in the pasteboard, construct a media item with that image and `send` it. let item = JSQPhotoMediaItem(image: UIPasteboard.generalPasteboard().image) let message = JSQMessage(senderId: self.senderId, senderDisplayName: self.senderDisplayName, date: NSDate(), media: item) self.conversation.messages.append(message) self.finishSendingMessage() return false } return true } }
mit
CNKCQ/oschina
Pods/SnapKit/Source/ConstraintAttributes.swift
1
7421
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif internal struct ConstraintAttributes: OptionSet { internal init(rawValue: UInt) { self.rawValue = rawValue } internal init(_ rawValue: UInt) { self.init(rawValue: rawValue) } internal init(nilLiteral _: ()) { rawValue = 0 } private(set) internal var rawValue: UInt internal static var allZeros: ConstraintAttributes { return self.init(0) } internal static func convertFromNilLiteral() -> ConstraintAttributes { return self.init(0) } internal var boolValue: Bool { return rawValue != 0 } internal func toRaw() -> UInt { return rawValue } internal static func fromRaw(_ raw: UInt) -> ConstraintAttributes? { return self.init(raw) } internal static func fromMask(_ raw: UInt) -> ConstraintAttributes { return self.init(raw) } // normal internal static var none: ConstraintAttributes { return self.init(0) } internal static var left: ConstraintAttributes { return self.init(1) } internal static var top: ConstraintAttributes { return self.init(2) } internal static var right: ConstraintAttributes { return self.init(4) } internal static var bottom: ConstraintAttributes { return self.init(8) } internal static var leading: ConstraintAttributes { return self.init(16) } internal static var trailing: ConstraintAttributes { return self.init(32) } internal static var width: ConstraintAttributes { return self.init(64) } internal static var height: ConstraintAttributes { return self.init(128) } internal static var centerX: ConstraintAttributes { return self.init(256) } internal static var centerY: ConstraintAttributes { return self.init(512) } internal static var lastBaseline: ConstraintAttributes { return self.init(1024) } @available(iOS 8.0, OSX 10.11, *) internal static var firstBaseline: ConstraintAttributes { return self.init(2048) } @available(iOS 8.0, *) internal static var leftMargin: ConstraintAttributes { return self.init(4096) } @available(iOS 8.0, *) internal static var rightMargin: ConstraintAttributes { return self.init(8192) } @available(iOS 8.0, *) internal static var topMargin: ConstraintAttributes { return self.init(16384) } @available(iOS 8.0, *) internal static var bottomMargin: ConstraintAttributes { return self.init(32768) } @available(iOS 8.0, *) internal static var leadingMargin: ConstraintAttributes { return self.init(65536) } @available(iOS 8.0, *) internal static var trailingMargin: ConstraintAttributes { return self.init(131_072) } @available(iOS 8.0, *) internal static var centerXWithinMargins: ConstraintAttributes { return self.init(262_144) } @available(iOS 8.0, *) internal static var centerYWithinMargins: ConstraintAttributes { return self.init(524_288) } // aggregates internal static var edges: ConstraintAttributes { return self.init(15) } internal static var size: ConstraintAttributes { return self.init(192) } internal static var center: ConstraintAttributes { return self.init(768) } @available(iOS 8.0, *) internal static var margins: ConstraintAttributes { return self.init(61440) } @available(iOS 8.0, *) internal static var centerWithinMargins: ConstraintAttributes { return self.init(786_432) } internal var layoutAttributes: [NSLayoutAttribute] { var attrs = [NSLayoutAttribute]() if contains(ConstraintAttributes.left) { attrs.append(.left) } if contains(ConstraintAttributes.top) { attrs.append(.top) } if contains(ConstraintAttributes.right) { attrs.append(.right) } if contains(ConstraintAttributes.bottom) { attrs.append(.bottom) } if contains(ConstraintAttributes.leading) { attrs.append(.leading) } if contains(ConstraintAttributes.trailing) { attrs.append(.trailing) } if contains(ConstraintAttributes.width) { attrs.append(.width) } if contains(ConstraintAttributes.height) { attrs.append(.height) } if contains(ConstraintAttributes.centerX) { attrs.append(.centerX) } if contains(ConstraintAttributes.centerY) { attrs.append(.centerY) } if contains(ConstraintAttributes.lastBaseline) { attrs.append(.lastBaseline) } #if os(iOS) || os(tvOS) if self.contains(ConstraintAttributes.firstBaseline) { attrs.append(.firstBaseline) } if self.contains(ConstraintAttributes.leftMargin) { attrs.append(.leftMargin) } if self.contains(ConstraintAttributes.rightMargin) { attrs.append(.rightMargin) } if self.contains(ConstraintAttributes.topMargin) { attrs.append(.topMargin) } if self.contains(ConstraintAttributes.bottomMargin) { attrs.append(.bottomMargin) } if self.contains(ConstraintAttributes.leadingMargin) { attrs.append(.leadingMargin) } if self.contains(ConstraintAttributes.trailingMargin) { attrs.append(.trailingMargin) } if self.contains(ConstraintAttributes.centerXWithinMargins) { attrs.append(.centerXWithinMargins) } if self.contains(ConstraintAttributes.centerYWithinMargins) { attrs.append(.centerYWithinMargins) } #endif return attrs } } internal func + (left: ConstraintAttributes, right: ConstraintAttributes) -> ConstraintAttributes { return left.union(right) } internal func +=(left: inout ConstraintAttributes, right: ConstraintAttributes) { left.formUnion(right) } internal func -=(left: inout ConstraintAttributes, right: ConstraintAttributes) { left.subtract(right) } internal func ==(left: ConstraintAttributes, right: ConstraintAttributes) -> Bool { return left.rawValue == right.rawValue }
mit
Jnosh/swift
test/reproducible-builds/swiftc-emit-ir.swift
3
240
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -O -g -module-name foo -emit-ir %s > %t/run-1.ir // RUN: %target-build-swift -O -g -module-name foo -emit-ir %s > %t/run-2.ir // RUN: diff -u %t/run-1.ir %t/run-2.ir print("foo")
apache-2.0
Danappelxx/MuttonChop
Tests/MuttonChopTests/TemplateCollectionTests.swift
1
2041
// // TemplateCollectionTests.swift // MuttonChop // // Created by Dan Appel on 11/1/16. // // import XCTest import Foundation @testable import MuttonChop var currentDirectory: String { return (NSString(string: #file)).deletingLastPathComponent + "/" } func fixture(name: String) throws -> Template? { let path = currentDirectory + "Fixtures/" + name guard let handle = FileHandle(forReadingAtPath: path), let fixture = String(data: handle.readDataToEndOfFile(), encoding: .utf8) else { return nil } return try Template(fixture) } class TemplateCollectionTests: XCTestCase { static var allTests: [(String, (TemplateCollectionTests) -> () throws -> Void)] { return [ ("testBasicCollection", testBasicCollection), ("testFileCollection", testFileCollection) ] } func testBasicCollection() throws { let collection = try TemplateCollection(templates: [ "conversation": fixture(name: "conversation.mustache")!, "greeting": fixture(name: "greeting.mustache")! ]) try testGetting(for: collection) try testRendering(for: collection) } func testFileCollection() throws { let collection = try TemplateCollection(directory: currentDirectory + "Fixtures") try testGetting(for: collection) try testRendering(for: collection) } func testGetting(for collection: TemplateCollection) throws { try XCTAssertEqual(collection.get(template: "conversation"), fixture(name: "conversation.mustache")!) try XCTAssertEqual(collection.get(template: "greeting"), fixture(name: "greeting.mustache")) } func testRendering(for collection: TemplateCollection) throws { try XCTAssertEqual("Hey there, Dan!", collection.render(template: "greeting", with: ["your-name": "Dan"])) try XCTAssertEqual("Hey there, Dan! My name is Billy.", collection.render(template: "conversation", with: ["your-name": "Dan", "my-name": "Billy"])) } }
mit
paketehq/ios
Pakete/UILabelExtensions.swift
1
1527
// // UILabelExtensions.swift // Pakete // // Created by Royce Albert Dy on 11/04/2016. // Copyright © 2016 Pakete. All rights reserved. // import Foundation extension UILabel { var adjustFontToRealIPhoneSize: Bool { set { if newValue { let currentFont = self.font var sizeScale: CGFloat = 1.0 if DeviceType.iPhone6 { sizeScale = 1.1 } else if DeviceType.iPhone6Plus { sizeScale = 1.2 } self.font = currentFont?.withSize((currentFont?.pointSize)! * sizeScale) } } get { return false } } } // TO DO: Transfer somewhere struct ScreenSize { static let ScreenWidth = UIScreen.main.bounds.size.width static let ScreenHeight = UIScreen.main.bounds.size.height static let ScreenMaxLength = max(ScreenSize.ScreenWidth, ScreenSize.ScreenHeight) static let ScreenMinLength = min(ScreenSize.ScreenHeight, ScreenSize.ScreenHeight) } struct DeviceType { static let iPhone4 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.ScreenMaxLength < 568.0 static let iPhone5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.ScreenMaxLength == 568.0 static let iPhone6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.ScreenMaxLength == 667.0 static let iPhone6Plus = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.ScreenMaxLength == 736.0 }
mit
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Model/Manager/ProductsModel.swift
1
27713
// // ProductsModel.swift // selluv-ios // // Created by 조백근 on 2017. 2. 6.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import SwiftyJSON import ObjectMapper import AlamofireObjectMapper import SwiftyUserDefaults class ProductsModel: NSObject { static let shared = ProductsModel() override init() { super.init() } //- 50. 상품상세 : GET /api/products/:_id case .productDetail(let productId): return "/api/product/\(productId)" /* case .productDetail(_) : return "{ \"status\": \"success\", \"data\": { \"_id\": \"YekoREze3AFzWa8Qh\", \"userId\": \"5PKwTeQq4PpwZjpd5\", \"category1\": { \"categoryId\": \"dxfRQFhDC9HqSqgBT\", \"name\": \"여성\" }, \"category2\": { \"categoryId\": \"8hCJfsZhFJCvEzACq\", \"name\": \"의류\" }, \"category3\": { \"categoryId\": \"fMfG2J7wRBBDB4zJD\", \"name\": \"탑/티셔츠\" }, \"category4\": { \"categoryId\": \"tkXRb8yRxXeAnYLTk\", \"name\": \"탱크탑\" }, \"brand\": { \"brandId\": \"wp8hBekgQFr5ZPrLw\", \"english\": \"WEEKEND MAX MARA\", \"korean\": \"위켄드 맥스 마라\" }, \"photos\": [ \"qgnjPwG8AcX7qC79C\" ], \"styles\": [ \"3TBBYLr7uDKGD6jS3\" ], \"sizeIndex\": 1, \"size\": [ \"XS\", \"38\", \"2\", \"6\" ], \"condition\": \"새상품\", \"damage\": [ \"얼룩 및 변색\", \"뜯어짐\" ], \"damages\": [ \"aejwBXYqcAEj3MHXF\" ], \"accessory\": [ \"게런티카드\", \"더스트백\" ], \"accessories\": [ \"dWhfWTnjTwu52JRDr\" ], \"color\": \"블랙\", \"model\": \"탱크탑\", \"description\": \"상품 설명\", \"tags\": [ \"여름\", \"여성\"], \"price\": { \"original\": 0, \"sell\": 500000, \"sail\": 0, \"depositAmount\": 0, \"settlementAmount\": 0, \"cardFees\": 0, \"selluvFees\": 0, \"promotion\": 0 }, \"seller\": { \"name\": \"셀럽\", \"phoneNo\": \"\", \"zip\": \"\", \"main\": \"\", \"sub\": \"\", \"bankName\": \"국민은행\", \"bankAccountNo\": \"12345678890\", \"bankAccountHoler\": {} }, \"isSoldOut\": false, \"isPhotoshop\": false, \"createdAt\": \"2016-12-20T05:30:09.875Z\", \"updatedAt\": \"2016-12-21T02:38:40.762Z\", \"likesCount\": 3, \"likes\": [ \"XDvzghae6mS53L4Qg\" ], \"ittemsCount\": 2, \"ittems\": [ \"XDvzghae6mS53L4Qg\" ] }}".data(using: String.Encoding.utf8)! */ func product(productId: String, completion: @escaping (_ success: Bool, _ info: SLVDetailProduct?)-> ()) { LoadingIndicatorView.show("Loading") BBProvider.sharedProvider.request(.productDetail(productId), queue: networkQueue, progress: progressClosure) { result in LoadingIndicatorView.hide() switch result { case let .success(moyaResponse): let resText = try? moyaResponse.mapString() let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etcq if statusCode == 200 { if let text = resText { let r: Response? = Response(JSONString: text) if r?.status == "success" { let info: SLVDetailProduct? = Mapper<SLVDetailProduct>().map(JSONObject: r!.data as! [String : Any]) completion(true, info) return } } } break case let .failure(error): log.error("Error: \(error.localizedDescription)") // AlertHelper.alert(message: error.localizedDescription) completion(false, nil) } } } //- 77. 추천 착용사진 목록 : GET /api/products/recommendation //case recommandProductsStylePhotos(String, String, String, Bool)// 77. 추천 착용사진 목록 func recommandProductsStylePhotos(cate1Id: String, cate2Id: String, brandId: String, isSame: Bool, block: @escaping (_ success: Bool, _ info: [SLVDetailProduct]?)-> ()) { LoadingIndicatorView.show("Loading") BBProvider.sharedProvider.request(.similarProducts(cate1Id, cate2Id, brandId, isSame), queue: networkQueue, progress: progressClosure) { result in LoadingIndicatorView.hide() switch result { case let .success(moyaResponse): let resText = try? moyaResponse.mapString() let data = moyaResponse.data // Data, your JSON response is probably in here! let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etcq if let txt = resText { let r: Response? = Response(JSONString: txt) if r?.status == "success" { log.debug(txt.debugDescription) let items: [SLVDetailProduct] = Mapper<SLVDetailProduct>().mapArray(JSONArray: r!.data! as! [[String : Any]])! block(true, items)//SLVDetailProduct return } } break case let .failure(error): log.error("Error: \(error.localizedDescription)") } block(false, nil) } } //- 78. 비슷한 상품 목록 : GET /api/products/brands/simularity //case similarProducts(String, String, String, Bool)//78. 비슷한 상품 목록 func similarProducts(brand: BrandP , isSame: Bool, block: @escaping (_ success: Bool, _ info: [SLVDetailProduct]?)-> ()) { LoadingIndicatorView.show("Loading") BBProvider.sharedProvider.request(.similarProducts(brand.brandId!, brand.english!, brand.korean!, isSame), queue: networkQueue, progress: progressClosure) { result in LoadingIndicatorView.hide() switch result { case let .success(moyaResponse): let resText = try? moyaResponse.mapString() let data = moyaResponse.data // Data, your JSON response is probably in here! let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etcq if let txt = resText { let r: Response? = Response(JSONString: txt) if r?.status == "success" { log.debug(txt.debugDescription) let items: [SLVDetailProduct] = Mapper<SLVDetailProduct>().mapArray(JSONArray: r!.data! as! [[String : Any]])! block(true, items)//SLVDetailProduct return } } break case let .failure(error): log.error("Error: \(error.localizedDescription)") } block(false, nil) } } //79. 판매자 상품 목록(상품목록 상세 및 판매자페이지: 아이템, 잇템, 스타일) : GET /api/seller/products/:_id //case anySellerProducts(String, String, Bool) //79. 판매자 상품 목록(상품목록 상세 및 판매자페이지: 아이템, 잇템, 스타일) : GET /api/seller/products/:_id func productsForSeller(userId: String, kind: String, isSame: Bool, block: @escaping (_ success: Bool, _ info: [SLVDetailProduct]?)-> ()) { LoadingIndicatorView.show("Loading") BBProvider.sharedProvider.request(.anySellerProducts(userId, kind, isSame), queue: networkQueue, progress: progressClosure) { result in LoadingIndicatorView.hide() switch result { case let .success(moyaResponse): var resText = try? moyaResponse.mapString() let data = moyaResponse.data // Data, your JSON response is probably in here! let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etcq //log.debug(resText?.description) if AppSetup.sharedState.isSimulator == true { let sample = "{\"status\":\"success\",\"data\":[{\"_id\":\"CbSQdDRMvWHWNDT75\",\"userId\":\"pfCmaJbeuzCnXmeFe\",\"category1\":{\"categoryId\":\"vxdqxGarn6yRYQmNw\",\"name\":\"여성\"},\"category2\":{\"categoryId\":\"ZQrnCDYiPjeD3GzpL\",\"name\":\"핸드백\"},\"category3\":{\"categoryId\":\"hReLh79XTPsC2sY9L\",\"name\":\"클러치\"},\"category4\":{\"categoryId\":\"\",\"name\":\"\"},\"brand\":{\"korean\":\"버버리\",\"brandId\":\"TdoLMzEFyRawdW5R5\",\"english\":\"BURBERRY\"},\"photos\":[\"NeGPW7LZMeWifGxxP.jpg\",\"hzHpDcNY8vL2WMfTs.jpg\",\"xtWWbEZqcyWGsrN5j.jpg\",\"Nzfo7EC7RhJfcCgt7.jpg\",\"9GfN56tzmqwgiHvkX.jpg\"], \"styles\":[\"NeGPW7LZMeWifGxxP.jpg\",\"hzHpDcNY8vL2WMfTs.jpg\",\"xtWWbEZqcyWGsrN5j.jpg\",\"Nzfo7EC7RhJfcCgt7.jpg\",\"9GfN56tzmqwgiHvkX.jpg\"], \"sizeIndex\":0,\"size\":[],\"damage\":[\"부자재 고장\",\"얼룩 및 변색\"],\"damages\":[],\"accessory\":[\"구매영수증\",\"여분부속품\"],\"accessories\":[],\"tags\":[],\"price\":{\"sale\":5526000,\"settlementAmount\":4862880,\"reserves\":97257.6,\"original\":5526000,\"cardFees\":165780,\"depositAmount\":4862880,\"promotion\":145886.4,\"selluvFees\":497340,\"sell\":0},\"signature\":\"G3nWBadaPGtay3wbF.jpg\",\"seller\":{\"main\":\"\",\"name\":\"\",\"phoneNo\":\"\",\"zip\":\"\",\"sub\":\"\",\"bankAccountNo\":\"44543\",\"bankAccountHolder\":\"cccc\",\"bankName\":\"우리은행\"},\"isSoldOut\":false,\"isPhotoshop\":false,\"likesCount\":0,\"likes\":[],\"ittemsCount\":0,\"ittems\":[],\"pageViewCount\":0,\"createdAt\":\"2017-02-09T06:11:22.860Z\",\"userInfo\":{\"avatar\":\"rec7Mn7PNh495y6qP.jpg\",\"nickname\":\"bbbb\"}},{\"_id\":\"EbFnR6NoEbQf5HmbT\",\"userId\":\"pfCmaJbeuzCnXmeFe\",\"category1\":{\"categoryId\":\"EyCMJujoZPdsALmkf\",\"name\":\"남성\"},\"category2\":{\"categoryId\":\"4EyAzH9eYu3hRLth7\",\"name\":\"슈즈\"},\"category3\":{\"categoryId\":\"STodGxYLa8gNTjeui\",\"name\":\"슬립온\"},\"category4\":{\"categoryId\":\"\",\"name\":\"\"},\"brand\":{\"korean\":\"버버리\",\"brandId\":\"TdoLMzEFyRawdW5R5\",\"english\":\"BURBERRY\"},\"photos\":[\"jYguxK6ZgNv5bZLZQ.jpg\"],\"sizeIndex\":0,\"size\":[],\"damage\":[],\"damages\":[],\"accessory\":[],\"accessories\":[],\"tags\":[],\"price\":{\"sale\":100000,\"settlementAmount\":88000,\"reserves\":1760,\"original\":100000,\"cardFees\":3000,\"depositAmount\":88000,\"promotion\":2640,\"selluvFees\":9000,\"sell\":0},\"signature\":\"G5oSG3ZJywZzwy6GB.jpg\",\"seller\":{\"main\":\"\",\"name\":\"\",\"phoneNo\":\"\",\"zip\":\"\",\"sub\":\"\",\"bankAccountNo\":\"11111111\",\"bankAccountHolder\":\"b\",\"bankName\":\"산업은행\"},\"isSoldOut\":false,\"isPhotoshop\":false,\"likesCount\":0,\"likes\":[],\"ittemsCount\":0,\"ittems\":[],\"pageViewCount\":0,\"createdAt\":\"2017-02-09T06:10:05.472Z\",\"userInfo\":{\"avatar\":\"rec7Mn7PNh495y6qP.jpg\",\"nickname\":\"bbbb\"}},{\"_id\":\"WxyqdREpjsZhyJCWA\",\"userId\":\"pfCmaJbeuzCnXmeFe\",\"category1\":{\"categoryId\":\"vxdqxGarn6yRYQmNw\",\"name\":\"여성\"},\"category2\":{\"categoryId\":\"NAcCHPj7H5W9CQSrH\",\"name\":\"패션소품\"},\"category3\":{\"categoryId\":\"WgS9qfDeXMhsR8oEp\",\"name\":\"벨트\"},\"category4\":{\"categoryId\":\"\",\"name\":\"\"},\"brand\":{\"korean\":\"구찌\",\"brandId\":\"AoR8kgM6AcBkdeMkw\",\"english\":\"GUCCI\"},\"photos\":[\"R5A8EW86iCJBnq9wp.jpg\",\"PXteF3K4cMinKgDj5.jpg\"],\"sizeIndex\":0,\"size\":[],\"damage\":[],\"damages\":[],\"accessory\":[],\"accessories\":[],\"tags\":[],\"price\":{\"sale\":100000,\"settlementAmount\":88000,\"reserves\":1760,\"original\":100000,\"cardFees\":3000,\"depositAmount\":88000,\"promotion\":2640,\"selluvFees\":9000,\"sell\":0},\"signature\":\"bPAgcqjHG7u5HdcNX.jpg\",\"seller\":{\"main\":\"\",\"name\":\"\",\"phoneNo\":\"\",\"zip\":\"\",\"sub\":\"\",\"bankAccountNo\":\"111111\",\"bankAccountHolder\":\"b\",\"bankName\":\"기업은행\"},\"isSoldOut\":false,\"isPhotoshop\":false,\"likesCount\":0,\"likes\":[],\"ittemsCount\":0,\"ittems\":[],\"pageViewCount\":0,\"createdAt\":\"2017-02-09T05:56:52.722Z\",\"userInfo\":{\"avatar\":\"rec7Mn7PNh495y6qP.jpg\",\"nickname\":\"bbbb\"}},{\"_id\":\"CA8jTRHZfPcYFSawx\",\"userId\":\"pfCmaJbeuzCnXmeFe\",\"category1\":{\"categoryId\":\"vxdqxGarn6yRYQmNw\",\"name\":\"여성\"},\"category2\":{\"categoryId\":\"Bph37eQ5QpK8b8EXr\",\"name\":\"슈즈\"},\"category3\":{\"categoryId\":\"yhJ2rGjaNcTCMEqK7\",\"name\":\"부츠\"},\"category4\":{\"categoryId\":\"\",\"name\":\"\"},\"brand\":{\"korean\":\"버버리\",\"brandId\":\"TdoLMzEFyRawdW5R5\",\"english\":\"BURBERRY\"},\"photos\":[\"xmmDT83vGBauzQi2n.jpg\",\"wrM4NZ2ccx4tHNrET.jpg\",\"zCqdMegTtTJbMvS4R.jpg\"],\"sizeIndex\":0,\"size\":[],\"condition\":\"최상급\",\"damage\":[\"구멍\",\"낡음\",\"늘어남\",\"뜯어짐\",\"수선\",\"스크래치\"],\"damages\":[],\"accessory\":[\"구매영수증\",\"브랜드박스\",\"상품택\",\"여분부속품\",\"ㅁㅁㅁㅁ\",\"ㅠㅠㅠㅠㅠ\"],\"accessories\":[],\"color\":\"그레이\",\"model\":\"ㅇㅇㅇㅇㅇㅇ\",\"tags\":[\"ㄸ\",\"ㅁ\",\"ㅠ\"],\"price\":{\"sale\":5097000,\"settlementAmount\":4485360,\"reserves\":89707.2,\"original\":5097000,\"cardFees\":152910,\"depositAmount\":4485360,\"promotion\":134560.8,\"selluvFees\":458730,\"sell\":0},\"signature\":\"L9w9eBjfL2mseqTAM.jpg\",\"seller\":{\"main\":\"\",\"name\":\"\",\"phoneNo\":\"\",\"zip\":\"\",\"sub\":\"\",\"bankAccountNo\":\"1231222\",\"bankAccountHolder\":\"jo\",\"bankName\":\"국민은행\"},\"isSoldOut\":false,\"isPhotoshop\":false,\"likesCount\":0,\"likes\":[],\"ittemsCount\":0,\"ittems\":[],\"pageViewCount\":0,\"createdAt\":\"2017-02-09T05:41:38.612Z\",\"userInfo\":{\"avatar\":\"rec7Mn7PNh495y6qP.jpg\",\"nickname\":\"bbbb\"}},{\"_id\":\"9ydTMLx6jWqBbwRSJ\",\"userId\":\"pfCmaJbeuzCnXmeFe\",\"category1\":{\"categoryId\":\"EyCMJujoZPdsALmkf\",\"name\":\"남성\"},\"category2\":{\"categoryId\":\"sDBRnrLZ3bCkRnpCM\",\"name\":\"시계/쥬얼리\"},\"category3\":{\"categoryId\":\"hs3QzxWXLrFLNJsux\",\"name\":\"시계\"},\"category4\":{\"categoryId\":\"\",\"name\":\"\"},\"brand\":{},\"photos\":[\"9q9YEHx9Gf6pxahyJ.jpg\",\"rfj2MRqMfuScc4NkL.jpg\"],\"sizeIndex\":0,\"size\":[],\"condition\":\"중상급\",\"damage\":[],\"damages\":[\"9QESFegC8esSMFG75.jpg\"],\"accessory\":[],\"accessories\":[\"dMbTiagSSZaRoA3kZ.jpg\"],\"color\":\"블랙\",\"model\":\"applewatch sport\",\"description\":\"apple watch sport 애플 홈페이지 구매\",\"tags\":[],\"price\":{\"sale\":0,\"settlementAmount\":0,\"reserves\":0,\"original\":0,\"cardFees\":0,\"depositAmount\":0,\"promotion\":0,\"selluvFees\":0,\"sell\":0},\"signature\":\"eikbQ39Jz5CLyqkgM.jpg\",\"seller\":{\"main\":\"\",\"name\":\"\",\"phoneNo\":\"\",\"zip\":\"\",\"sub\":\"\",\"bankAccountNo\":\"222222222\",\"bankAccountHolder\":\"benjamin\",\"bankName\":\"산업은행\"},\"isSoldOut\":true,\"isPhotoshop\":false,\"likesCount\":0,\"likes\":[],\"ittemsCount\":0,\"ittems\":[],\"pageViewCount\":0,\"createdAt\":\"2017-02-08T15:22:33.812Z\",\"updatedAt\":\"2017-02-09T02:28:02.385Z\",\"userInfo\":{\"avatar\":\"rec7Mn7PNh495y6qP.jpg\",\"nickname\":\"bbbb\"}}, {\"_id\":\"CbSQdDRMvWHWNDT75\",\"userId\":\"pfCmaJbeuzCnXmeFe\",\"category1\":{\"categoryId\":\"vxdqxGarn6yRYQmNw\",\"name\":\"여성\"},\"category2\":{\"categoryId\":\"ZQrnCDYiPjeD3GzpL\",\"name\":\"핸드백\"},\"category3\":{\"categoryId\":\"hReLh79XTPsC2sY9L\",\"name\":\"클러치\"},\"category4\":{\"categoryId\":\"\",\"name\":\"\"},\"brand\":{\"korean\":\"버버리\",\"brandId\":\"TdoLMzEFyRawdW5R5\",\"english\":\"BURBERRY\"},\"photos\":[\"NeGPW7LZMeWifGxxP.jpg\",\"hzHpDcNY8vL2WMfTs.jpg\",\"xtWWbEZqcyWGsrN5j.jpg\",\"Nzfo7EC7RhJfcCgt7.jpg\",\"9GfN56tzmqwgiHvkX.jpg\"],\"sizeIndex\":0,\"size\":[],\"damage\":[\"부자재 고장\",\"얼룩 및 변색\"],\"damages\":[],\"accessory\":[\"구매영수증\",\"여분부속품\"],\"accessories\":[],\"tags\":[],\"price\":{\"sale\":5526000,\"settlementAmount\":4862880,\"reserves\":97257.6,\"original\":5526000,\"cardFees\":165780,\"depositAmount\":4862880,\"promotion\":145886.4,\"selluvFees\":497340,\"sell\":0},\"signature\":\"G3nWBadaPGtay3wbF.jpg\",\"seller\":{\"main\":\"\",\"name\":\"\",\"phoneNo\":\"\",\"zip\":\"\",\"sub\":\"\",\"bankAccountNo\":\"44543\",\"bankAccountHolder\":\"cccc\",\"bankName\":\"우리은행\"},\"isSoldOut\":false,\"isPhotoshop\":false,\"likesCount\":0,\"likes\":[],\"ittemsCount\":0,\"ittems\":[],\"pageViewCount\":0,\"createdAt\":\"2017-02-09T06:11:22.860Z\",\"userInfo\":{\"avatar\":\"rec7Mn7PNh495y6qP.jpg\",\"nickname\":\"bbbb\"}},{\"_id\":\"EbFnR6NoEbQf5HmbT\",\"userId\":\"pfCmaJbeuzCnXmeFe\",\"category1\":{\"categoryId\":\"EyCMJujoZPdsALmkf\",\"name\":\"남성\"},\"category2\":{\"categoryId\":\"4EyAzH9eYu3hRLth7\",\"name\":\"슈즈\"},\"category3\":{\"categoryId\":\"STodGxYLa8gNTjeui\",\"name\":\"슬립온\"},\"category4\":{\"categoryId\":\"\",\"name\":\"\"},\"brand\":{\"korean\":\"버버리\",\"brandId\":\"TdoLMzEFyRawdW5R5\",\"english\":\"BURBERRY\"},\"photos\":[\"jYguxK6ZgNv5bZLZQ.jpg\"],\"styles\":[\"NeGPW7LZMeWifGxxP.jpg\",\"hzHpDcNY8vL2WMfTs.jpg\",\"xtWWbEZqcyWGsrN5j.jpg\",\"Nzfo7EC7RhJfcCgt7.jpg\",\"9GfN56tzmqwgiHvkX.jpg\"],\"sizeIndex\":0,\"size\":[],\"damage\":[],\"damages\":[],\"accessory\":[],\"accessories\":[],\"tags\":[],\"price\":{\"sale\":100000,\"settlementAmount\":88000,\"reserves\":1760,\"original\":100000,\"cardFees\":3000,\"depositAmount\":88000,\"promotion\":2640,\"selluvFees\":9000,\"sell\":0},\"signature\":\"G5oSG3ZJywZzwy6GB.jpg\",\"seller\":{\"main\":\"\",\"name\":\"\",\"phoneNo\":\"\",\"zip\":\"\",\"sub\":\"\",\"bankAccountNo\":\"11111111\",\"bankAccountHolder\":\"b\",\"bankName\":\"산업은행\"},\"isSoldOut\":false,\"isPhotoshop\":false,\"likesCount\":0,\"likes\":[],\"ittemsCount\":0,\"ittems\":[],\"pageViewCount\":0,\"createdAt\":\"2017-02-09T06:10:05.472Z\",\"userInfo\":{\"avatar\":\"rec7Mn7PNh495y6qP.jpg\",\"nickname\":\"bbbb\"}},{\"_id\":\"WxyqdREpjsZhyJCWA\",\"userId\":\"pfCmaJbeuzCnXmeFe\",\"category1\":{\"categoryId\":\"vxdqxGarn6yRYQmNw\",\"name\":\"여성\"},\"category2\":{\"categoryId\":\"NAcCHPj7H5W9CQSrH\",\"name\":\"패션소품\"},\"category3\":{\"categoryId\":\"WgS9qfDeXMhsR8oEp\",\"name\":\"벨트\"},\"category4\":{\"categoryId\":\"\",\"name\":\"\"},\"brand\":{\"korean\":\"구찌\",\"brandId\":\"AoR8kgM6AcBkdeMkw\",\"english\":\"GUCCI\"},\"photos\":[\"R5A8EW86iCJBnq9wp.jpg\",\"PXteF3K4cMinKgDj5.jpg\"],\"sizeIndex\":0,\"size\":[],\"damage\":[],\"damages\":[],\"accessory\":[],\"accessories\":[],\"tags\":[],\"price\":{\"sale\":100000,\"settlementAmount\":88000,\"reserves\":1760,\"original\":100000,\"cardFees\":3000,\"depositAmount\":88000,\"promotion\":2640,\"selluvFees\":9000,\"sell\":0},\"signature\":\"bPAgcqjHG7u5HdcNX.jpg\",\"seller\":{\"main\":\"\",\"name\":\"\",\"phoneNo\":\"\",\"zip\":\"\",\"sub\":\"\",\"bankAccountNo\":\"111111\",\"bankAccountHolder\":\"b\",\"bankName\":\"기업은행\"},\"isSoldOut\":false,\"isPhotoshop\":false,\"likesCount\":0,\"likes\":[],\"ittemsCount\":0,\"ittems\":[],\"pageViewCount\":0,\"createdAt\":\"2017-02-09T05:56:52.722Z\",\"userInfo\":{\"avatar\":\"rec7Mn7PNh495y6qP.jpg\",\"nickname\":\"bbbb\"}},{\"_id\":\"CA8jTRHZfPcYFSawx\",\"userId\":\"pfCmaJbeuzCnXmeFe\",\"category1\":{\"categoryId\":\"vxdqxGarn6yRYQmNw\",\"name\":\"여성\"},\"category2\":{\"categoryId\":\"Bph37eQ5QpK8b8EXr\",\"name\":\"슈즈\"},\"category3\":{\"categoryId\":\"yhJ2rGjaNcTCMEqK7\",\"name\":\"부츠\"},\"category4\":{\"categoryId\":\"\",\"name\":\"\"},\"brand\":{\"korean\":\"버버리\",\"brandId\":\"TdoLMzEFyRawdW5R5\",\"english\":\"BURBERRY\"},\"photos\":[\"xmmDT83vGBauzQi2n.jpg\",\"wrM4NZ2ccx4tHNrET.jpg\",\"zCqdMegTtTJbMvS4R.jpg\"],\"sizeIndex\":0,\"size\":[],\"condition\":\"최상급\",\"damage\":[\"구멍\",\"낡음\",\"늘어남\",\"뜯어짐\",\"수선\",\"스크래치\"],\"damages\":[],\"accessory\":[\"구매영수증\",\"브랜드박스\",\"상품택\",\"여분부속품\",\"ㅁㅁㅁㅁ\",\"ㅠㅠㅠㅠㅠ\"],\"accessories\":[],\"color\":\"그레이\",\"model\":\"ㅇㅇㅇㅇㅇㅇ\",\"tags\":[\"ㄸ\",\"ㅁ\",\"ㅠ\"],\"price\":{\"sale\":5097000,\"settlementAmount\":4485360,\"reserves\":89707.2,\"original\":5097000,\"cardFees\":152910,\"depositAmount\":4485360,\"promotion\":134560.8,\"selluvFees\":458730,\"sell\":0},\"signature\":\"L9w9eBjfL2mseqTAM.jpg\",\"seller\":{\"main\":\"\",\"name\":\"\",\"phoneNo\":\"\",\"zip\":\"\",\"sub\":\"\",\"bankAccountNo\":\"1231222\",\"bankAccountHolder\":\"jo\",\"bankName\":\"국민은행\"},\"isSoldOut\":false,\"isPhotoshop\":false,\"likesCount\":0,\"likes\":[],\"ittemsCount\":0,\"ittems\":[],\"pageViewCount\":0,\"createdAt\":\"2017-02-09T05:41:38.612Z\",\"userInfo\":{\"avatar\":\"rec7Mn7PNh495y6qP.jpg\",\"nickname\":\"bbbb\"}},{\"_id\":\"9ydTMLx6jWqBbwRSJ\",\"userId\":\"pfCmaJbeuzCnXmeFe\",\"category1\":{\"categoryId\":\"EyCMJujoZPdsALmkf\",\"name\":\"남성\"},\"category2\":{\"categoryId\":\"sDBRnrLZ3bCkRnpCM\",\"name\":\"시계/쥬얼리\"},\"category3\":{\"categoryId\":\"hs3QzxWXLrFLNJsux\",\"name\":\"시계\"},\"category4\":{\"categoryId\":\"\",\"name\":\"\"},\"brand\":{},\"photos\":[\"9q9YEHx9Gf6pxahyJ.jpg\",\"rfj2MRqMfuScc4NkL.jpg\"],\"sizeIndex\":0,\"size\":[],\"condition\":\"중상급\",\"damage\":[],\"damages\":[\"9QESFegC8esSMFG75.jpg\"],\"accessory\":[],\"accessories\":[\"dMbTiagSSZaRoA3kZ.jpg\"],\"color\":\"블랙\",\"model\":\"applewatch sport\",\"description\":\"apple watch sport 애플 홈페이지 구매\",\"tags\":[],\"price\":{\"sale\":0,\"settlementAmount\":0,\"reserves\":0,\"original\":0,\"cardFees\":0,\"depositAmount\":0,\"promotion\":0,\"selluvFees\":0,\"sell\":0},\"signature\":\"eikbQ39Jz5CLyqkgM.jpg\",\"seller\":{\"main\":\"\",\"name\":\"\",\"phoneNo\":\"\",\"zip\":\"\",\"sub\":\"\",\"bankAccountNo\":\"222222222\",\"bankAccountHolder\":\"benjamin\",\"bankName\":\"산업은행\"},\"isSoldOut\":true,\"isPhotoshop\":false,\"likesCount\":0,\"likes\":[],\"ittemsCount\":0,\"ittems\":[],\"pageViewCount\":0,\"createdAt\":\"2017-02-08T15:22:33.812Z\",\"updatedAt\":\"2017-02-09T02:28:02.385Z\",\"userInfo\":{\"avatar\":\"rec7Mn7PNh495y6qP.jpg\",\"nickname\":\"bbbb\"}}]}" resText = sample } if let txt = resText { let r: Response? = Response(JSONString: txt) if r?.status == "success" { log.debug(txt.debugDescription) let items: [SLVDetailProduct] = Mapper<SLVDetailProduct>().mapArray(JSONArray: r!.data! as! [[String : Any]])! block(true, items)//SLVDetailProduct return } } break case let .failure(error): log.error("Error: \(error.localizedDescription)") } block(false, nil) } } // - 40. 댓글목록 : GET /api/comments/:_id //case comments(String) //40. 댓글목록 //productId //40. 댓글목록 // case .comments(_) : return "{ \"status\": \"success\", \"data\": [ { \"_id\": \"HMXq3xCbhRXjaTZCd\", \"productId\": \"QNbiJGHSGaeXnNhMs\", \"writerId\": \"MeR9ykzzcfWidaMDi\", \"text\": \"댓글 등록3\", \"createdAt\": \"2016-12-12T04:51:47.401Z\" }, { \"_id\": \"RiSXA7wb5eNwb95dy\", \"productId\": \"QNbiJGHSGaeXnNhMs\", \"writerId\": \"MeR9ykzzcfWidaMDi\", \"text\": \"댓글 등록2\", \"createdAt\": \"2016-12-12T04:51:30.271Z\" }, { \"_id\": \"PsvE9fbxjwqEpiMKP\", \"productId\": \"QNbiJGHSGaeXnNhMs\", \"writerId\": \"MeR9ykzzcfWidaMDi\", \"text\": \"댓글 등록\", \"createdAt\": \"2016-12-12T04:40:16.013Z\", \"reply\": { \"replyId\": \"YsXw3nYNpdRoZ2Nig\", \"text\": \"답글 등록\", \"createdAt\": \"2016-12-12T04:50:35.342Z\" } } ]}".data(using: String.Encoding.utf8)! func comments(productId: String, block: @escaping (_ success: Bool, _ info: [SLVComment]?)-> ()) { LoadingIndicatorView.show("Loading") BBProvider.sharedProvider.request(.comments(productId), queue: networkQueue, progress: progressClosure) { result in LoadingIndicatorView.hide() switch result { case let .success(moyaResponse): let resText = try? moyaResponse.mapString() let data = moyaResponse.data // Data, your JSON response is probably in here! let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etcq if let txt = resText { let r: Response? = Response(JSONString: txt) if r?.status == "success" { log.debug(txt.debugDescription) let items: [SLVComment] = Mapper<SLVComment>().mapArray(JSONArray: r!.data! as! [[String : Any]])! block(true, items)//SLVDetailProduct return } } break case let .failure(error): log.error("Error: \(error.localizedDescription)") } block(false, nil) } } // - 41. 댓글등록 : POST /api/comments // case newComments(String, String, String) // case let .newComments(productId, writerId, text): return [ "productId": productId, "writerId": writerId, "text": text ] func newComment(productId: String, text: String, completion: @escaping (_ success: Bool)-> ()) { LoadingIndicatorView.show("Loading") let user = BBAuthToken.shared.name() BBProvider.sharedProvider.request(.newComments(productId, user, text), queue: networkQueue, progress: progressClosure) { result in LoadingIndicatorView.hide() switch result { case let .success(moyaResponse): let resText = try? moyaResponse.mapString() let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etcq if statusCode == 200 { if let text = resText { let r: Response? = Response(JSONString: text) if r?.status == "success" { completion(true) return } } } break case let .failure(error): log.error("Error: \(error.localizedDescription)") // AlertHelper.alert(message: error.localizedDescription) } completion(false) } } // - 42. 답글등록 : PUT /api/comments/reply // case newReply(String, String, String) // case let .newReply(commentId, replyId, text): return [ "commentId": commentId, "replyId": replyId, "text": text ] func newReply(thatgulId: String, text: String, completion: @escaping (_ success: Bool)-> ()) { LoadingIndicatorView.show("Loading") let user = BBAuthToken.shared.name() BBProvider.sharedProvider.request(.newReply(thatgulId, user, text), queue: networkQueue, progress: progressClosure) { result in LoadingIndicatorView.hide() switch result { case let .success(moyaResponse): let resText = try? moyaResponse.mapString() let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etcq if statusCode == 200 { if let text = resText { let r: Response? = Response(JSONString: text) if r?.status == "success" { completion(true) return } } } break case let .failure(error): log.error("Error: \(error.localizedDescription)") // AlertHelper.alert(message: error.localizedDescription) } completion(false) } } }
mit
SwiftKit/Reactant
Source/Core/Component/ComponentBase.swift
2
1309
// // ComponentBase.swift // Reactant // // Created by Filip Dolnik on 08.11.16. // Copyright © 2016 Brightify. All rights reserved. // import RxSwift open class ComponentBase<STATE, ACTION>: ComponentWithDelegate { public typealias StateType = STATE public typealias ActionType = ACTION public let lifetimeDisposeBag = DisposeBag() public let componentDelegate = ComponentDelegate<STATE, ACTION, ComponentBase<STATE, ACTION>>() open var action: Observable<ACTION> { return componentDelegate.action } /** * Collection of Component's `Observable`s which are merged into `Component.action`. * - Note: When listening to Component's actions, using `action` is preferred to `actions`. */ open var actions: [Observable<ACTION>] { return [] } open func needsUpdate() -> Bool { return true } public init(canUpdate: Bool = true) { componentDelegate.ownerComponent = self resetActions() afterInit() componentDelegate.canUpdate = canUpdate } open func afterInit() { } open func update() { } public func observeState(_ when: ObservableStateEvent) -> Observable<STATE> { return componentDelegate.observeState(when) } }
mit
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Controllers/Review Prompt/ReviewPromptAction.swift
1
88
import Foundation public protocol ReviewPromptAction { func showReviewPrompt() }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/09260-swift-constraints-constraintsystem-finalize.swift
11
328
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct A { let a = " " b { } class b { struct A { { } { { { } { { } { } } { { { } } { } { } } } { } { } { { } { } } { { } } } enum B { protocol A : a { func a
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/12688-swift-sourcemanager-getmessage.swift
11
252
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing init( ) { enum S { func f { let f = { deinit { protocol a { class B { class case ,
mit
HolidayAdvisorIOS/HolidayAdvisor
HolidayAdvisor/HolidayAdvisor/PlaceDetailsViewController.swift
1
1529
// // PlaceDetailsViewController.swift // HolidayAdvisor // // Created by Iliyan Gogov on 4/3/17. // Copyright © 2017 Iliyan Gogov. All rights reserved. // import UIKit class PlaceDetailsViewController: UIViewController { @IBOutlet weak var placeImage: UIImageView! @IBOutlet weak var placeNameLabel: UILabel! @IBOutlet weak var placeInfoLabel: UILabel! @IBOutlet weak var placeOwnerLabel: UILabel! var name : String? = "" var imageUrl: String? = "" var info: String? = "" var owner: String? = "" var rating: Int? = 0 override func viewDidLoad() { super.viewDidLoad() self.placeNameLabel.text = self.name self.placeOwnerLabel.text = self.owner self.placeInfoLabel.text = self.info if let url = NSURL(string: self.imageUrl!) { if let data = NSData(contentsOf: url as URL) { self.placeImage?.image = UIImage(data: data as Data) } } } 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
danielmartin/swift
stdlib/private/SwiftPrivate/IO.swift
2
3406
//===----------------------------------------------------------------------===// // // 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift import SwiftShims public struct _FDInputStream { public let fd: CInt public var isClosed: Bool = false public var isEOF: Bool = false internal var _buffer = [UInt8](repeating: 0, count: 256) internal var _bufferUsed: Int = 0 public init(fd: CInt) { self.fd = fd } public mutating func getline() -> String? { if let newlineIndex = _buffer[0..<_bufferUsed].firstIndex(of: UInt8(Unicode.Scalar("\n").value)) { let result = String(decoding: _buffer[0..<newlineIndex], as: UTF8.self) _buffer.removeSubrange(0...newlineIndex) _bufferUsed -= newlineIndex + 1 return result } if isEOF && _bufferUsed > 0 { let result = String(decoding: _buffer[0..<_bufferUsed], as: UTF8.self) _buffer.removeAll() _bufferUsed = 0 return result } return nil } public mutating func read() { let minFree = 128 var bufferFree = _buffer.count - _bufferUsed if bufferFree < minFree { _buffer.reserveCapacity(minFree - bufferFree) while bufferFree < minFree { _buffer.append(0) bufferFree += 1 } } let fd = self.fd let readResult: __swift_ssize_t = _buffer.withUnsafeMutableBufferPointer { (_buffer) in let addr = _buffer.baseAddress! + self._bufferUsed let size = bufferFree return _swift_stdlib_read(fd, addr, size) } if readResult == 0 { isEOF = true return } if readResult < 0 { fatalError("read() returned error") } _bufferUsed += readResult } public mutating func close() { if isClosed { return } let result = _swift_stdlib_close(fd) if result < 0 { fatalError("close() returned an error") } isClosed = true } } public struct _Stderr : TextOutputStream { public init() {} public mutating func write(_ string: String) { for c in string.utf8 { _swift_stdlib_putc_stderr(CInt(c)) } } } public struct _FDOutputStream : TextOutputStream { public let fd: CInt public var isClosed: Bool = false public init(fd: CInt) { self.fd = fd } public mutating func write(_ string: String) { let utf8CStr = string.utf8CString utf8CStr.withUnsafeBufferPointer { (utf8CStr) -> Void in var writtenBytes = 0 let bufferSize = utf8CStr.count - 1 while writtenBytes != bufferSize { let result = _swift_stdlib_write( self.fd, UnsafeRawPointer(utf8CStr.baseAddress! + Int(writtenBytes)), bufferSize - writtenBytes) if result < 0 { fatalError("write() returned an error") } writtenBytes += result } } } public mutating func close() { if isClosed { return } let result = _swift_stdlib_close(fd) if result < 0 { fatalError("close() returned an error") } isClosed = true } }
apache-2.0
ask-fm/AFMActionSheet
Pod/Classes/AFMPresentationAnimator.swift
1
2219
// // AFMPresentationAnimator.swift // Pods // // Created by Ilya Alesker on 26/08/15. // Copyright (c) 2015 Ask.fm Europe, Ltd. All rights reserved. // import UIKit open class AFMPresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning { open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 1.0 } open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! as UIViewController let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! as UIViewController let finalFrame = transitionContext.initialFrame(for: fromViewController) toViewController.view.frame = finalFrame transitionContext.containerView.addSubview(toViewController.view) let views = toViewController.view.subviews let viewCount = Double(views.count) var index = 0 let step: Double = self.transitionDuration(using: transitionContext) * 0.5 / viewCount for view in views { view.transform = CGAffineTransform(translationX: 0, y: finalFrame.height) let delay = step * Double(index) UIView.animate(withDuration: self.transitionDuration(using: transitionContext) - delay, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.3, options: [], animations: { view.transform = CGAffineTransform.identity; }, completion: nil) index += 1 } let backgroundColor = toViewController.view.backgroundColor! toViewController.view.backgroundColor = backgroundColor.withAlphaComponent(0) UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: { toViewController.view.backgroundColor = backgroundColor }, completion: { _ in transitionContext.completeTransition(true) }) } }
mit
22377832/swiftdemo
StretchDemo/StretchDemo/AppDelegate.swift
1
2170
// // AppDelegate.swift // StretchDemo // // Created by adults on 2017/3/22. // Copyright © 2017年 adults. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. } }
mit
idomizrachi/Regen
regen/General Models/Tree.swift
1
453
// // Tree.swift // regen // // Created by Ido Mizrachi on 10/3/17. // Copyright © 2017 Ido Mizrachi. All rights reserved. // import Cocoa public class TreeNode<T> { public let item: T public private(set) var children: [TreeNode<T>] = [] public init(item: T) { self.item = item } public func addChild(_ child: TreeNode<T>) { self.children.append(child) } } public class Tree<T>: TreeNode<T> { }
mit
jsslai/Action
Demo/DemoTests/BarButtonTests.swift
2
2671
import Quick import Nimble import RxSwift import RxBlocking import Action class BarButtonTests: QuickSpec { override func spec() { it("is nil by default") { let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil) expect(subject.rx_action).to( beNil() ) } it("respects setter") { let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil) let action = emptyAction() subject.rx_action = action expect(subject.rx_action) === action } it("disables the button while executing") { let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil) var observer: AnyObserver<Void>! let action = CocoaAction(workFactory: { _ in return Observable.create { (obsv) -> Disposable in observer = obsv return NopDisposable.instance } }) subject.rx_action = action action.execute() expect(subject.enabled).toEventually( beFalse() ) observer.onCompleted() expect(subject.enabled).toEventually( beTrue() ) } it("disables the button if the Action is disabled") { let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil) subject.rx_action = emptyAction(.just(false)) expect(subject.enabled) == false } it("doesn't execute a disabled action when tapped") { let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil) var executed = false subject.rx_action = CocoaAction(enabledIf: .just(false), workFactory: { _ in executed = true return .empty() }) subject.target?.performSelector(subject.action, withObject: subject) expect(executed) == false } it("executes the action when tapped") { let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil) var executed = false let action = CocoaAction(workFactory: { _ in executed = true return .empty() }) subject.rx_action = action subject.target?.performSelector(subject.action, withObject: subject) expect(executed) == true } it("disposes of old action subscriptions when re-set") { let subject = UIBarButtonItem(barButtonSystemItem: .Save, target: nil, action: nil) var disposed = false autoreleasepool { let disposeBag = DisposeBag() let action = emptyAction() subject.rx_action = action action .elements .subscribe(onNext: nil, onError: nil, onCompleted: nil, onDisposed: { disposed = true }) .addDisposableTo(disposeBag) } subject.rx_action = nil expect(disposed) == true } } }
mit
everald/JetPack
Sources/Extensions/Foundation/URLQueryItem.swift
2
187
import Foundation extension Sequence where Iterator.Element == URLQueryItem { public func first(named name: String) -> URLQueryItem? { return firstMatching { $0.name == name } } }
mit
broccolii/NipponColors
ColorPicker/ViewController/ColorListViewController.swift
1
14378
// // ColorListViewController.swift // ColorPicker // // Created by Broccoli on 15/11/2. // Copyright © 2015年 Broccoli. All rights reserved. // import UIKit class ColorListViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var lblColorName: UILabel! @IBOutlet weak var lblBottomConstraint: NSLayoutConstraint! @IBOutlet weak var lblWidthConstraint: NSLayoutConstraint! var dataArr = [ColorInfo]() // 隐藏 状态栏 override func prefersStatusBarHidden() -> Bool { return true } // MARK: - Life cycle override func loadView() { super.loadView() // 在 viewdidload 之前 调用 prepareForSegue 所以 需要 提前 读取到 数据 readColorInfoData() } override func viewDidLoad() { super.viewDidLoad() // 添加 页面数据 view.backgroundColor = UIColor(red: CGFloat(dataArr[0].RValue) / 255.0, green: CGFloat(dataArr[0].GValue) / 255.0, blue: CGFloat(dataArr[0].BValue) / 255.0, alpha: 1.0) lblColorName.text = dataArr[0].colorName addOverLayer() screenAdaptation() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ColorPropertyTableViewController" { let VC = segue.destinationViewController as! ColorPropertyTableViewController VC.colorInfo = dataArr[0] } } // MARK: - private method /// 读取 颜色数据 func readColorInfoData() { let path = NSBundle.mainBundle().pathForResource("ColorInfoData", ofType: nil) let data = NSData(contentsOfFile: path!) do { let jsonArr = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! Array<[String: String]> for (index, value) in jsonArr.enumerate() { dataArr.append(ColorInfo.dicToModel(value, index: index)) } } catch let error as NSError { print(error) } } /// 愚蠢的版本适配 private func screenAdaptation() { // TODO: - 考虑 用最小 约束 修改适配 if UIScreen.mainScreen().bounds.width == 320 { lblWidthConstraint.constant = 60 lblColorName.font = UIFont(name: "HeiseiMinStd-W7", size: 35.0) if UIScreen.mainScreen().bounds.height == 480 { lblColorName.hidden = true } } else { lblBottomConstraint.constant = 20 lblColorName.font = UIFont(name: "HeiseiMinStd-W7", size: 43.0) } } // 添加 宣纸样式的遮罩 private func addOverLayer() { let overLayer = UIImageView() overLayer.frame = UIScreen.mainScreen().bounds overLayer.image = UIImage(named: "blurLayer") overLayer.alpha = 0.4 view.insertSubview(overLayer, aboveSubview: lblColorName) } } private let CellIdentifier = "ColorCollectionViewCell" // MARK: - UICollectionViewDataSource extension ColorListViewController: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataArr.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellIdentifier, forIndexPath: indexPath) as! ColorCollectionViewCell // 清空 cell 之前的 view 和 layer // TODO: - 为了 VC 代码 简洁 这个可以写成 cell 的方法 for view in cell.subviews { view.removeFromSuperview() } if let sublayer = cell.layer.sublayers { for layer in sublayer { layer.removeFromSuperlayer() } } cell.colorInfo = dataArr[indexPath.row] return cell } } // MARK: - UICollectionViewDelegate extension ColorListViewController: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // 系统自带动画 修改 lblColorName 的 透明度 文本 并且通知 下方 属性栏 开始动画 UIView.animateWithDuration(1.2, animations: { () -> Void in self.lblColorName.alpha = 0.0 }) { (finish) -> Void in self.lblColorName.text = self.dataArr[indexPath.row].colorName UIView.animateWithDuration(1.8, animations: { () -> Void in self.lblColorName.alpha = 1.0 NSNotificationCenter.defaultCenter().postNotificationName("kChangeColorProperty", object: nil, userInfo: ["colorInfo" : self.dataArr[indexPath.row]]) }) } // POP 动画修改颜色 let animation = POPBasicAnimation(propertyNamed: kPOPLayerBackgroundColor) animation.toValue = UIColor(red: CGFloat(dataArr[indexPath.row].RValue) / 255.0, green: CGFloat(dataArr[indexPath.row].GValue) / 255.0, blue: CGFloat(dataArr[indexPath.row].BValue) / 255.0, alpha: 1.0) animation.duration = 2.5 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) self.view.layer.pop_addAnimation(animation, forKey: nil) collectionView.reloadItemsAtIndexPaths([indexPath]) } } /// MARK: - ColorCollectionViewCell class ColorCollectionViewCell: UICollectionViewCell { @IBOutlet var lblRGBValue: UILabel! @IBOutlet var lblRGBName: UILabel! var colorInfo: ColorInfo! { didSet { createRBGValue() createColorName() createColorCount() createEnglishName() drawMaskLayer() beginAnimation() } } /// 绘制 layer 的基础 data private let moveToPointArr = [CGPoint(x: 22, y: 195), CGPoint(x: 27, y: 195), CGPoint(x: 32, y: 195)] private let addLineToPointArr = [CGPoint(x: 22, y: 360), CGPoint(x: 27, y: 360), CGPoint(x: 32, y: 360)] private let arcCenterArr = [CGPoint(x: 18, y: 39), CGPoint(x: 18, y: 81), CGPoint(x: 18, y: 123), CGPoint(x: 18, y: 165)] /// RGB 线段 private lazy var lineLayerArr: [CAShapeLayer]! = { var arr = [CAShapeLayer]() for i in 0 ..< 3 { let linePath = UIBezierPath() linePath.moveToPoint(self.moveToPointArr[i]) linePath.addLineToPoint(self.addLineToPointArr[i]) linePath.closePath() let lineLayer = CAShapeLayer() lineLayer.strokeColor = UIColor(white: 1.0, alpha: 0.7).CGColor lineLayer.lineWidth = 2.0 lineLayer.path = linePath.CGPath arr.append(lineLayer) } return arr }() /// CMYK 圆弧 private lazy var shapeLayerArr: [CAShapeLayer]! = { var arr = [CAShapeLayer]() for i in 0 ..< 4 { let path = UIBezierPath(arcCenter: self.arcCenterArr[i], radius: 12, startAngle: CGFloat(-M_PI / 2), endAngle: CGFloat(M_PI * 3 / 2), clockwise: true) let shapeLayer = CAShapeLayer() shapeLayer.strokeColor = UIColor.whiteColor().CGColor shapeLayer.fillColor = UIColor.clearColor().CGColor shapeLayer.path = path.CGPath shapeLayer.lineWidth = 8.0 arr.append(shapeLayer) } return arr }() override func drawRect(rect: CGRect) { super.drawRect(rect) let ctx = UIGraphicsGetCurrentContext() // draw base white circle CGContextSetLineWidth(ctx, 8) CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 0.2) CGContextAddArc(ctx, 18, 39, 12, 0, CGFloat(2 * M_PI), 0) CGContextDrawPath(ctx, CGPathDrawingMode.Stroke) CGContextAddArc(ctx, 18, 81, 12, 0, CGFloat(2 * M_PI), 0) CGContextDrawPath(ctx, CGPathDrawingMode.Stroke) CGContextAddArc(ctx, 18, 123, 12, 0, CGFloat(2 * M_PI), 0) CGContextDrawPath(ctx, CGPathDrawingMode.Stroke) CGContextAddArc(ctx, 18, 165, 12, 0, CGFloat(2 * M_PI), 0) CGContextDrawPath(ctx, CGPathDrawingMode.Stroke) // RGB 数值 线 CGContextSetLineWidth(ctx, 2) CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 0.2) let pointsValue1 = [CGPoint(x: 22, y: 195), CGPoint(x: 22, y: 360)] CGContextAddLines(ctx, pointsValue1, 2) let pointsValue2 = [CGPoint(x: 27, y: 195), CGPoint(x: 27, y: 360)] CGContextAddLines(ctx, pointsValue2, 2) let pointsValue3 = [CGPoint(x: 32, y: 195), CGPoint(x: 32, y: 360)] CGContextAddLines(ctx, pointsValue3, 2) CGContextStrokePath(ctx) } /// 绘制 底层视图 private func drawMaskLayer() { for lineLayer in lineLayerArr { layer.addSublayer(lineLayer) } for shapeLayer in shapeLayerArr { layer.addSublayer(shapeLayer) } // draw color view let colorView = CALayer() colorView.frame = CGRect(x: 0, y: 0, width: 60, height: 8) colorView.backgroundColor = UIColor(red: CGFloat(colorInfo.RValue) / 255.0, green: CGFloat(colorInfo.GValue) / 255.0, blue: CGFloat(colorInfo.BValue) / 255.0, alpha: 1.0).CGColor self.layer.addSublayer(colorView) } } // MARK: - create widget extension ColorCollectionViewCell { // 创建 颜色 英文名 private func createEnglishName() { let lblEN = UILabel(frame: CGRect(x: 60 - 17, y: 195 + 17, width: 165, height: 17)) lblEN.font = UIFont(name: "DeepdeneBQ-Roman", size: 17.0) lblEN.textColor = UIColor(white: 1.0, alpha: 0.9) lblEN.text = colorInfo.colorEN lblEN.layer.anchorPoint = CGPoint(x: 0, y: 1) lblEN.layer.position = CGPoint(x: 60 - 17, y: 195) lblEN.transform = CGAffineTransformMakeRotation(CGFloat(M_PI / 2)) self.addSubview(lblEN) } // 创建 颜色 RGB 值 private func createRBGValue() { let lblRGB = UILabel(frame: CGRect(x: 0, y: 195 + 9, width: 55, height: 11)) lblRGB.font = UIFont.systemFontOfSize(11.0) lblRGB.textColor = UIColor(white: 1.0, alpha: 0.9) lblRGB.text = colorInfo.RBGHexValue lblRGB.layer.anchorPoint = CGPoint(x: 0, y: 1) lblRGB.layer.position = CGPoint(x: 0, y: 195) lblRGB.transform = CGAffineTransformMakeRotation(CGFloat(M_PI / 2)) self.addSubview(lblRGB) } // 创建 颜色 编号 private func createColorCount() { let lblCount = UILabel(frame: CGRect(x: 60, y: 23, width: 30, height: 13)) lblCount.font = UIFont.systemFontOfSize(13.0) lblCount.textColor = UIColor(red: CGFloat(colorInfo.RValue) / 255.0, green: CGFloat(colorInfo.GValue) / 255.0, blue: CGFloat(colorInfo.BValue) / 255.0, alpha: 1.0) lblCount.text = colorInfo.colorCount lblCount.layer.anchorPoint = CGPoint(x: 0, y: 0) lblCount.layer.position = CGPoint(x: 60, y: 23) lblCount.transform = CGAffineTransformMakeRotation(CGFloat(M_PI / 2)) self.addSubview(lblCount) } // 创建 颜色 中文名 private func createColorName() { let lblName = UILabel(fontname: "HeiseiMinStd-W7", labelText: colorInfo.colorName, fontSize: 17.0) lblName.textColor = UIColor(white: 1.0, alpha: 0.9) lblName.frame = CGRect(x: 60 - CGRectGetWidth(lblName.bounds), y: 180 - CGRectGetHeight(lblName.bounds), width: CGRectGetWidth(lblName.bounds), height: CGRectGetHeight(lblName.bounds)) self.addSubview(lblName) } } // MARK: - Add Animation extension ColorCollectionViewCell { private func beginAnimation() { /// 添加 线段 的动画 let lineAnimationToValueArr = [CGFloat(colorInfo.RValue) / 255.0 / 2.0, CGFloat(colorInfo.GValue) / 255.0 / 2.0, CGFloat(colorInfo.BValue) / 255.0 / 2.0] lineLayerAddAnimation(lineAnimationToValueArr) /// 添加 圆弧 的动画 let shapeLayerToValueArr = [CGFloat(colorInfo.CValue) / 100.0, CGFloat(colorInfo.MValue) / 100.0, CGFloat(colorInfo.YValue) / 100.0, CGFloat(colorInfo.KValue) / 100.0] shapeLayerAddAnimation(shapeLayerToValueArr) } private func lineLayerAddAnimation(toValueArr: [CGFloat]) { for (i, lineLayer) in lineLayerArr.enumerate() { let lineAnimation = POPBasicAnimation(propertyNamed: kPOPShapeLayerStrokeEnd) lineAnimation.fromValue = 0.5 lineAnimation.toValue = toValueArr[i] lineAnimation.duration = 1.0 lineAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) lineLayer.pop_addAnimation(lineAnimation, forKey: "strokeEnd") } } private func shapeLayerAddAnimation(toValueArr: [CGFloat]) { for (i, shapeLayer) in shapeLayerArr.enumerate() { let animation = POPBasicAnimation(propertyNamed: kPOPShapeLayerStrokeEnd) animation.fromValue = 1.0 animation.toValue = toValueArr[i] animation.duration = 3.0 animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.12, 1, 0.11, 0.94) shapeLayer.pop_addAnimation(animation, forKey: "shapeLayer1Animation") } } } extension UILabel { // 生成 竖向文本 水平居下对齐 convenience init(fontname: String ,labelText: String, fontSize :CGFloat) { let font = UIFont(name: fontname, size: fontSize) as UIFont! let textAttributes: [String : AnyObject] = [NSFontAttributeName: font] let labelSize = labelText.boundingRectWithSize(CGSizeMake(fontSize, 480), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textAttributes, context: nil) self.init(frame: labelSize) self.attributedText = NSAttributedString(string: labelText, attributes: textAttributes) self.lineBreakMode = NSLineBreakMode.ByCharWrapping self.numberOfLines = 0 } }
mit
StartAppsPe/StartAppsKitExtensions
Sources/OptionalExtensions.swift
1
818
// // OptionalExtensions.swift // StartAppsKitExtensionsPackageDescription // // Created by Gabriel Lanata on 12/10/17. // import Foundation public enum OptionalError: LocalizedError { case unwrappingNone(String?) public var errorDescription: String? { switch self { case .unwrappingNone(let errorMessage): return errorMessage ?? "Optional value does not exist".localized } } } extension Optional { public func tryUnwrap(errorMessage: String? = nil) throws -> Wrapped { switch self { case .some(let value): return value case .none: throw OptionalError.unwrappingNone(errorMessage) } } } postfix operator † public postfix func †<T>(_ a: T?) throws -> T { return try a.tryUnwrap() }
mit
drunknbass/Emby.ApiClient.Swift
Emby.ApiClient/apiinteraction/discovery/ServerLocatorProtocol.swift
2
227
// // ServerLocatorProtocol.swift // EmbyApiClient import Foundation public protocol ServerDiscoveryProtocol { func findServers(timeoutMs: Int, onSuccess: ([ServerDiscoveryInfo]) -> Void, onError: (ErrorType) -> Void) }
mit
12207480/TYPagerController
TYPagerControllerDemo_swift/TabPagerControllerDemoController.swift
1
1679
// // TabPagerControllerDemoController.swift // TYPagerControllerDemo_swift // // Created by tany on 2017/7/19. // Copyright © 2017年 tany. All rights reserved. // import UIKit class TabPagerControllerDemoController: TYTabPagerController { lazy var datas = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.tabBar.layout.barStyle = TYPagerBarStyle.progressView self.dataSource = self self.delegate = self self.loadData() } func loadData() { var i = 0 while i < 20 { self.datas.append(i%2==0 ?"Tab \(i)":"Tab Tab \(i)") i += 1 } self.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension TabPagerControllerDemoController: TYTabPagerControllerDataSource, TYTabPagerControllerDelegate { func numberOfControllersInTabPagerController() -> Int { return self.datas.count } func tabPagerController(_ tabPagerController: TYTabPagerController, controllerFor index: Int, prefetching: Bool) -> UIViewController { let vc = UIViewController() vc.view.backgroundColor = UIColor(red: CGFloat(arc4random()%255)/255.0, green: CGFloat(arc4random()%255)/255.0, blue: CGFloat(arc4random()%255)/255.0, alpha: 1) return vc } func tabPagerController(_ tabPagerController: TYTabPagerController, titleFor index: Int) -> String { let title = self.datas[index] return title } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/01842-swift-associatedtypedecl-associatedtypedecl.swift
1
503
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol A : a { func i> { let x } var a: b(e(a func i(start, ") var b = A, U) -> Any) { } typealias b {
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/00678-swift-availabilityattr-isunavailable.swift
1
490
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol c : d { typealias d: C = a() { enum B = """) func c<Y> (Any, q:Any) { } class a())
apache-2.0
cnoon/swift-compiler-crashes
crashes-duplicates/14484-swift-sourcemanager-getmessage.swift
11
238
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { ( { class a { struct c< { deinit { protocol d { class case ,
mit
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/Browse WFS layers/WFSLayersTableViewController.swift
1
9179
// Copyright 2019 Esri. // // 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 import ArcGIS class WFSLayersTableViewController: UITableViewController { // Every layer info that could be used to create a WFSFeatureTable var allLayerInfos: [AGSWFSLayerInfo] = [] // MapView to display the map with WFS features var mapView: AGSMapView? // Layer Info for the layer that is currently drawn on map view var selectedLayerInfo: AGSWFSLayerInfo? private var shouldSwapCoordinateOrder = false private var lastQuery: AGSCancelable? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let selectedLayerInfo = selectedLayerInfo, let selectedRow = allLayerInfos.firstIndex(of: selectedLayerInfo) { let selectedIndexPath = IndexPath(row: selectedRow, section: 0) tableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .middle) tableView.cellForRow(at: selectedIndexPath)?.accessoryType = .checkmark } } // A convenience type for the table view sections. private enum Section: Int { case operational, swapCoordinateOrder var label: String { switch self { case .operational: return "Operational Layers" case .swapCoordinateOrder: return "Coordinate Order" } } } // MARK: - UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return Section(rawValue: section)?.label } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Section(rawValue: section)! { case .operational: return allLayerInfos.count case .swapCoordinateOrder: return 1 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch Section(rawValue: indexPath.section)! { case .operational: let cell = tableView.dequeueReusableCell(withIdentifier: "LayerCell", for: indexPath) let layerInfo = allLayerInfos[indexPath.row] cell.textLabel?.text = layerInfo.title cell.accessoryType = (tableView.indexPathForSelectedRow == indexPath) ? .checkmark : .none return cell case .swapCoordinateOrder: let cell: SettingsTableViewCell = (tableView.dequeueReusableCell(withIdentifier: "SettingsCell", for: indexPath) as? SettingsTableViewCell)! cell.swapCoordinateOrderSwitch.addTarget(self, action: #selector(switchChanged(_:)), for: .valueChanged) return cell } } @objc func switchChanged(_ swapSwitch: UISwitch) { // Keep track of whether coordinate order should be swapped self.shouldSwapCoordinateOrder = swapSwitch.isOn // Check if there is a layer selected if tableView.indexPathForSelectedRow != nil { // Query for features taking into account the updated swap order, and display the layer displaySelectedLayer() } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let selectedCell = tableView.cellForRow(at: indexPath), indexPath.section == 0 else { return } // add a checkmark to the selected cell selectedCell.accessoryType = .checkmark if self.selectedLayerInfo != allLayerInfos[indexPath.row] { // Get the selected layer info. self.selectedLayerInfo = allLayerInfos[indexPath.row] // Query for features and display the selected layer displaySelectedLayer() } } override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if indexPath.section == 0 { tableView.cellForRow(at: indexPath)?.accessoryType = .none } } // MARK: - Helper Method func displaySelectedLayer() { // Check if selected layer info is non-nil guard let selectedLayerInfo = self.selectedLayerInfo else { return } // Create a WFS feature table with the layer info let wfsFeatureTable = AGSWFSFeatureTable(layerInfo: selectedLayerInfo) // Set the feature request mode to manual - only manual is supported at v100.5. // In this mode, you must manually populate the table - panning and zooming won't request features automatically. wfsFeatureTable.featureRequestMode = .manualCache // Set the axis order based on the UI. It is by default false. wfsFeatureTable.axisOrder = self.shouldSwapCoordinateOrder ? .swap : .noSwap // If there is an existing query request, cancel it if let lastQuery = self.lastQuery { lastQuery.cancel() } // Create query parameters let params = AGSQueryParameters() params.whereClause = "1=1" // Show progress UIApplication.shared.showProgressHUD(message: "Querying") // Populate features based on query self.lastQuery = wfsFeatureTable.populateFromService(with: params, clearCache: true, outFields: ["*"]) { [weak self] (result: AGSFeatureQueryResult?, error: Error?) in guard let self = self else { return } // Check and get results if let result = result, let mapView = self.mapView { // The resulting features should be displayed on the map // Print the count of features print("Populated \(result.featureEnumerator().allObjects.count) features.") // Create a feature layer from the WFS table. let wfsFeatureLayer = AGSFeatureLayer(featureTable: wfsFeatureTable) // Choose a renderer for the layer wfsFeatureLayer.renderer = AGSSimpleRenderer.random(wfsFeatureTable) // Replace map's operational layer mapView.map?.operationalLayers.setArray([wfsFeatureLayer]) // Zoom to the extent of the layer mapView.setViewpointGeometry(selectedLayerInfo.extent!, padding: 50.0) } // Check for error. If it's a user canceled error, do nothing. // Otherwise, display an alert. else if let error = error { if (error as NSError).code != NSUserCancelledError { self.presentAlert(error: error) } else { return } } // Hide Progress UIApplication.shared.hideProgressHUD() } } } private extension AGSSimpleRenderer { /// Creates a renderer appropriate for the geometry type of the table, /// and symbolizes the renderer with a random color /// /// - Returns: A new `AGSSimpleRenderer` object. static func random(_ table: AGSFeatureTable) -> AGSSimpleRenderer? { switch table.geometryType { case .point, .multipoint: let simpleMarkerSymbol = AGSSimpleMarkerSymbol(style: .circle, color: .random(), size: 4.0) return AGSSimpleRenderer(symbol: simpleMarkerSymbol) case .polyline: let simpleLineSymbol = AGSSimpleLineSymbol(style: .solid, color: .random(), width: 1.0) return AGSSimpleRenderer(symbol: simpleLineSymbol) case .polygon, .envelope: let simpleFillSymbol = AGSSimpleFillSymbol(style: .solid, color: .random(), outline: nil) return AGSSimpleRenderer(symbol: simpleFillSymbol) default: return nil } } } private extension UIColor { /// Creates a random color whose red, green, and blue values are in the /// range `0...1` and whose alpha value is `1`. /// /// - Returns: A new `UIColor` object. static func random() -> UIColor { let range: ClosedRange<CGFloat> = 0...1 return UIColor(red: .random(in: range), green: .random(in: range), blue: .random(in: range), alpha: 1) } } class SettingsTableViewCell: UITableViewCell { @IBOutlet weak var swapCoordinateOrderSwitch: UISwitch! }
apache-2.0
hsavit1/LeetCode-Solutions-in-Swift
Solutions/Solutions/Medium/Medium_079_Word_Search.swift
1
2032
/* https://leetcode.com/problems/word-search/ #79 Word Search Level: medium Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = [ ["ABCE"], ["SFCS"], ["ADEE"] ] word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false. Inspired by @pavel-shlyk at https://leetcode.com/discuss/23165/accepted-very-short-java-solution-no-additional-space */ import Foundation private extension String { subscript (index: Int) -> Character { return self[advance(self.startIndex, index)] } } struct Medium_079_Word_Search { static func exist(var board: [[Character]], word: String) -> Bool { for var x = 0; x < board.count; x++ { for var y = 0; y < board[x].count; y++ { if exist_recursion_helper(board: &board, x: x, y: y, word: word, i: 0) { return true } } } return false } static private func exist_recursion_helper(inout board board: [[Character]], x: Int, y: Int, word: String, i: Int) -> Bool { if i == word.characters.count { return true } if x < 0 || y < 0 || x == board.count || y == board[x].count { return false } if board[x][y] != word[i] { return false } let tmp: Character = board[x][y] board[x][y] = "_" let exist: Bool = exist_recursion_helper(board: &board, x: x, y: y+1, word: word, i: i+1) || exist_recursion_helper(board: &board, x: x, y: y-1, word: word, i: i+1) || exist_recursion_helper(board: &board, x: x-1, y: y, word: word, i: i+1) || exist_recursion_helper(board: &board, x: x+1, y: y, word: word, i: i+1) board[x][y] = tmp return exist } }
mit
ziogaschr/swift-sodium
Sodium/Bytes.swift
2
462
import Foundation public typealias Bytes = Array<UInt8> extension Array where Element == UInt8 { init (count bytes: Int) { self.init(repeating: 0, count: bytes) } public var utf8String: String? { return String(data: Data(bytes: self), encoding: .utf8) } } extension ArraySlice where Element == UInt8 { var bytes: Bytes { return Bytes(self) } } public extension String { var bytes: Bytes { return Bytes(self.utf8) } }
isc
nodes-ios/Sourcery
Sourcery/Sourcery/Classes/Sourcery/ComplexSourcery.swift
1
4365
// // ComplexSourcery.swift // Sourcery // // Created by Dominik Hádl on 27/04/16. // Copyright © 2016 Nodes ApS. All rights reserved. // import UIKit open class ComplexSourcery: NSObject, TableController { public typealias HeaderConfigurator = ((_ section: Int, _ header: UITableViewHeaderFooterView?, _ title: String?) -> Void) open fileprivate(set) weak var tableView: UITableView? /// Setting a custom height will override the height of all cells to the value specified. /// If the value is nil, the `staticHeight` property of each cell will be used instead. var autoDeselect = true /// TODO: Documentation open fileprivate(set) var sections: [SectionType] { didSet { tableView?.reloadData() } } /// TODO: Documentation var headerHeight: CGFloat = 32.0 /// TODO: Documentation fileprivate var headerConfigurator: HeaderConfigurator? /// If set, then some UITableView delegate methods will be sent to it. open var delegateProxy: TableViewDelegateProxy? // MARK: - Init - fileprivate override init() { fatalError("Never instantiate this class directly. Use the init(tableView:sections:) initializer.") } public required init(tableView: UITableView, sections: [SectionType], headerConfigurator: HeaderConfigurator? = nil) { self.tableView = tableView self.sections = sections self.headerConfigurator = headerConfigurator super.init() self.tableView?.dataSource = self self.tableView?.delegate = self self.tableView?.reloadData() } // MARK: - Update Data - open func update(sections newSections: [SectionType]) { sections = newSections tableView?.reloadData() } // MARK: - UITableView Data Source & Delegate - open func numberOfSections(in tableView: UITableView) -> Int { return sections.count } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].dataCount } open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return sections[indexPath.section].heightForCell(atIndex: indexPath.row) } open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section].title } open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // If we have a header, return its height return sections[section].headerType?.staticHeight ?? (sections[section].title != nil ? headerHeight : 0) } open func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { // If we have a header, return its height return sections[section].headerType?.staticHeight ?? (sections[section].title != nil ? headerHeight : 0) } open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // If a header is specified - dequeue, configure and return it if let type = sections[section].headerType { let header = tableView.dequeueHeaderFooterView(type) headerConfigurator?(section, header, sections[section].title) return header } return nil } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let customConstructors = sections[indexPath.section].customConstructors if customConstructors.count > indexPath.row { let constructor = customConstructors[indexPath.row] return constructor!(tableView, indexPath.row) } let type = sections[indexPath.section].cellType let cell = tableView.dequeueDefault(cellType: type) sections[indexPath.section].configure(cell: cell, index: indexPath.row) return cell } open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if autoDeselect { tableView.deselectRow(at: indexPath, animated: true) } sections[indexPath.section].handle(selection: indexPath.row) } open func scrollViewDidScroll(_ scrollView: UIScrollView) { delegateProxy?.scrollViewDidScroll(scrollView) } }
mit
brentdax/swift
stdlib/public/core/HeapBuffer.swift
3
2624
//===----------------------------------------------------------------------===// // // 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims @usableFromInline // FIXME(sil-serialize-all) internal typealias _HeapObject = SwiftShims.HeapObject @usableFromInline internal protocol _HeapBufferHeader_ { associatedtype Value init(_ value: Value) var value: Value { get set } } @_fixed_layout // FIXME(sil-serialize-all) @usableFromInline internal struct _HeapBufferHeader<T> : _HeapBufferHeader_ { @usableFromInline // FIXME(sil-serialize-all) internal typealias Value = T @inlinable // FIXME(sil-serialize-all) internal init(_ value: T) { self.value = value } @usableFromInline // FIXME(sil-serialize-all) internal var value: T } @usableFromInline internal typealias _HeapBuffer<Value,Element> = ManagedBufferPointer<_HeapBufferHeader<Value>, Element> @usableFromInline internal typealias _HeapBufferStorage<Value,Element> = ManagedBuffer<_HeapBufferHeader<Value>, Element> extension ManagedBufferPointer where Header : _HeapBufferHeader_ { @usableFromInline // FIXME(sil-serialize-all) internal typealias Value = Header.Value @inlinable // FIXME(sil-serialize-all) internal init( _ storageClass: AnyClass, _ initializer: Value, _ capacity: Int ) { self.init( _uncheckedBufferClass: storageClass, minimumCapacity: capacity) self.withUnsafeMutablePointerToHeader { $0.initialize(to: Header(initializer)) } } @inlinable // FIXME(sil-serialize-all) internal var value: Value { @inline(__always) get { return header.value } @inline(__always) set { return header.value = newValue } } @inlinable // FIXME(sil-serialize-all) internal subscript(i: Int) -> Element { @inline(__always) get { return withUnsafeMutablePointerToElements { $0[i] } } } @inlinable // FIXME(sil-serialize-all) internal var baseAddress: UnsafeMutablePointer<Element> { @inline(__always) get { return withUnsafeMutablePointerToElements { $0 } } } @inlinable // FIXME(sil-serialize-all) internal var storage: AnyObject? { @inline(__always) get { return buffer } } }
apache-2.0
tardieu/swift
test/ClangImporter/CoreGraphics_test.swift
3
6417
// RUN: %target-swift-frontend -target x86_64-apple-macosx10.11 -module-name=cgtest -emit-ir -O %s | %FileCheck %s // Test some imported CG APIs import CoreGraphics // REQUIRES: OS=macosx // CHECK: [[SWITCHTABLE:@.*]] = private unnamed_addr constant [8 x i64] [i64 0, i64 12, i64 23, i64 34, i64 45, i64 55, i64 67, i64 71] // CHECK-LABEL: define i64 {{.*}}testEnums{{.*}} { public func testEnums(_ model: CGColorSpaceModel) -> Int { switch model { case .unknown : return 0 case .monochrome : return 12 case .rgb : return 23 case .cmyk : return 34 case .lab : return 45 case .deviceN : return 55 case .indexed : return 67 case .pattern : return 71 default: return 0 } // CHECK: [[GEP:%.+]] = getelementptr inbounds [8 x i64], [8 x i64]* [[SWITCHTABLE]], i64 0, i64 %{{.*}} // CHECK: [[LOAD:%.+]] = load i64, i64* [[GEP]], align 8 // CHECK: ret i64 [[LOAD]] } // CHECK-LABEL: define void {{.*}}rotationAround{{.*}} { // Get a transform that will rotate around a given offset public func rotationAround(offset: CGPoint, angle: CGFloat, transform: CGAffineTransform = .identity) -> CGAffineTransform { // FIXME: consistent API namings return transform.translatedBy(x: offset.x, y: offset.y) .rotated(by: angle) .translatedBy(x: -offset.x, y: -offset.y) // CHECK: call void @CGAffineTransformTranslate(%{{.*}}.CGAffineTransform* {{.*}}, %{{.*}}.CGAffineTransform* {{.*}},{{.*}}, {{.*}}) // CHECK: call void @CGAffineTransformRotate(%{{.*}}.CGAffineTransform* {{.*}}, %{{.*}}.CGAffineTransform* {{.*}},{{.*}}) // CHECK: call void @CGAffineTransformTranslate(%{{.*}}.CGAffineTransform* {{.*}}, %{{.*}}.CGAffineTransform* {{.*}},{{.*}}, {{.*}}) // // CHECK: ret void } // CHECK-LABEL: define void {{.*}}trace{{.*}} { public func trace(in context: CGContext, path: CGPath) { let red = CGColor(red: 1, green: 0, blue: 0, alpha: 1) context.saveGState() context.addPath(path) context.setStrokeColor(red) context.strokePath() context.restoreGState() // CHECK: call %{{.*}}.CGColor* @CGColorCreateGenericRGB(double 1.000000e+00, double 0.000000e+00, double 0.000000e+00, double 1.000000e+00) // CHECK: call void @CGContextSaveGState(%{{.*}}.CGContext* %{{.*}}) // CHECK: call void @CGContextAddPath(%{{.*}}.CGContext* %{{.*}}, %{{.*}}.CGPath* %{{.*}}) // CHECK: call void @CGContextSetStrokeColorWithColor(%{{.*}}.CGContext* %{{.*}}, %{{.*}}.CGColor* %{{.*}}) // CHECK: call void @CGContextStrokePath(%{{.*}}.CGContext* %{{.*}}) // CHECK: call void @CGContextRestoreGState(%{{.*}}.CGContext* %{{.*}}) // // CHECK: ret void } // CHECK-LABEL: define void {{.*}}pdfOperations{{.*}} { public func pdfOperations(_ context: CGContext) { context.beginPDFPage(nil) context.endPDFPage() context.closePDF() // CHECK: call void @CGPDFContextBeginPage(%{{.*}}.CGContext* %{{.*}}, %{{.*}}.__CFDictionary* {{.*}}) // CHECK: call void @CGPDFContextEndPage(%{{.*}}.CGContext* %{{.*}}) // CHECK: call void @CGPDFContextClose(%{{.*}}.CGContext* %{{.*}}) // // CHECK: ret void } // Test some more recently renamed APIs // CHECK-LABEL: define void {{.*}}testColorRenames{{.*}} { public func testColorRenames(color: CGColor, intent: CGColorRenderingIntent) { let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)! // CHECK: %{{.*}} = load {{.*}}%struct.__CFString** @kCGColorSpaceSRGB {{.*}}, align 8 // CHECK: %{{.*}} = {{.*}} call %struct.CGColorSpace* @CGColorSpaceCreateWithName(%struct.__CFString* %{{.*}}) let _ = color.converted(to: colorSpace, intent: intent, options: nil) // CHECK: %{{.*}} = {{.*}} call %struct.CGColor* @CGColorCreateCopyByMatchingToColorSpace(%struct.CGColorSpace* nonnull %{{.*}}, i32 %{{.*}}, %struct.CGColor* %{{.*}}, %struct.__CFDictionary* null) // // CHECK: ret void } // CHECK-LABEL: define void {{.*}}testRenames{{.*}} { public func testRenames(transform: CGAffineTransform, context: CGContext, point: CGPoint, size: CGSize, rect: CGRect, image: CGImage, edge: CGRectEdge) { let transform = transform.inverted().concatenating(transform) // CHECK: call void @CGAffineTransformInvert(%struct.CGAffineTransform* {{.*}}, %struct.CGAffineTransform* {{.*}}) // CHECK: call void @CGAffineTransformConcat(%struct.CGAffineTransform* {{.*}}, %struct.CGAffineTransform* {{.*}}, %struct.CGAffineTransform* {{.*}}) let _ = point.applying(transform) var rect = rect.applying(transform) let _ = size.applying(transform) // CHECK: %{{.*}} = call { double, double } @CGPointApplyAffineTransform(double %{{.*}}, double %{{.*}}, %struct.CGAffineTransform* {{.*}}) // CHECK: call void @CGRectApplyAffineTransform(%struct.CGRect* {{.*}}, %struct.CGRect* {{.*}}, %struct.CGAffineTransform* {{.*}}) // CHECK: %{{.*}} = call { double, double } @CGSizeApplyAffineTransform(double %{{.*}}, double %{{.*}}, %struct.CGAffineTransform* {{.*}}) context.concatenate(transform) context.rotate(by: CGFloat.pi) context.scaleBy(x: 1.0, y: 1.0) context.translateBy(x: 1.0, y: 1.0) // CHECK: call void @CGContextConcatCTM(%struct.CGContext* [[CONTEXT:%[0-9]+]], %struct.CGAffineTransform* {{.*}}) // CHECK: call void @CGContextRotateCTM(%struct.CGContext* [[CONTEXT]], double {{.*}}) // CHECK: call void @CGContextScaleCTM(%struct.CGContext* [[CONTEXT]], double {{1\.0+.*}}, double {{1\.0+.*}}) // CHECK: call void @CGContextTranslateCTM(%struct.CGContext* [[CONTEXT]], double {{1\.0+.*}}, double {{1\.0+.*}}) context.clip(to: rect) context.clip(to: rect, mask: image) // CHECK: call void @CGContextClipToRect(%struct.CGContext* [[CONTEXT]], %struct.CGRect* byval nonnull align 8 %{{.*}}) // CHECK: call void @CGContextClipToMask(%struct.CGContext* [[CONTEXT]], %struct.CGRect* byval nonnull align 8 %{{.*}}, %struct.CGImage* %{{.*}}) var slice = CGRect.zero var remainder = CGRect.zero rect.__divided(slice: &slice, remainder: &remainder, atDistance: CGFloat(2.0), from: edge) assert((slice, remainder) == rect.divided(atDistance: CGFloat(2.0), from: edge)) // CHECK: call void @CGRectDivide(%struct.CGRect* byval nonnull align 8 %{{.*}}, %struct.CGRect* nonnull %{{.*}}, %struct.CGRect* nonnull %{{.*}}, double {{2\.0+.*}}, i32 %{{.*}}) // // CHECK: ret void }
apache-2.0
juancazalla/DI-Frameworks-iOS
DI&Frameworks/MovieDetailsViewModel.swift
1
417
// // MovieDetailsViewModel.swift // DI&Frameworks // // Created by Juan Cazalla Estrella on 16/5/16. // Copyright © 2016 Juan Cazalla Estrella. All rights reserved. // import Foundation import Domain protocol MovieDetailsViewModelType { var movie: Movie { get } } struct MovieDetailsViewModel: MovieDetailsViewModelType { let movie: Movie init(movie: Movie) { self.movie = movie } }
apache-2.0
asalom/Cocoa-Design-Patterns-in-Swift
DesignPatterns/DesignPatterns/Basic/Dynamic Creation/DynamicCommandA.swift
1
280
// // DynamicA.swift // DesignPatterns // // Created by Alex Salom on 05/11/15. // Copyright © 2015 Alex Salom © alexsalom.es. All rights reserved. // class DynamicCommandA: DynamicCommand { override class func command() -> String { return "Command A" } }
mit
alvesjtiago/hnr
HNR/Models/Job.swift
1
756
// // Job.swift // HNR // // Created by Tiago Alves on 17/09/2017. // Copyright © 2017 Tiago Alves. All rights reserved. // import UIKit class Job: NSObject { var id: Int? var title: String? var text: String? var score: Int? var by: String? var url: URL? convenience init(json: NSDictionary) { self.init() id = json.value(forKey: "id") as? Int title = json.value(forKey: "title") as? String text = json.value(forKey: "text") as? String score = json.value(forKey: "score") as? Int by = json.value(forKey: "by") as? String if let urlString = json.value(forKey: "url") as? String { url = URL(string: urlString) } } }
mit
dreymonde/SwiftyNURE
Sources/SwiftyNURE/Model/Subject.swift
1
417
// // Subject.swift // NUREAPI // // Created by Oleg Dreyman on 18.02.16. // Copyright © 2016 Oleg Dreyman. All rights reserved. // import Foundation public struct Subject { public let id: Int public let name: String public let shortName: String public init(name: String, shortName: String, id: Int) { self.name = name self.shortName = shortName self.id = id } }
mit
gavrix/ImageViewModel
Carthage/Checkouts/ReactiveSwift/.Package.test.swift
1
418
import PackageDescription let package = Package( name: "ReactiveSwift", dependencies: [ .Package(url: "https://github.com/antitypical/Result.git", majorVersion: 3), .Package(url: "https://github.com/Quick/Quick", majorVersion: 1), .Package(url: "https://github.com/Quick/Nimble", majorVersion: 5, minor: 1), ], exclude: [ "Sources/Deprecations+Removals.swift", ] )
mit
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0120.xcplaygroundpage/Contents.swift
2
6776
/*: # Revise `partition` Method Signature * Proposal: [SE-0120](0120-revise-partition-method.md) * Authors: [Lorenzo Racca](https://github.com/lorenzoracca), [Jeff Hajewski](https://github.com/j-haj), [Nate Cook](https://github.com/natecook1000) * Review Manager: [Chris Lattner](http://github.com/lattner) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-July/000242.html) * Bug: [SR-1965](https://bugs.swift.org/browse/SR-1965) * Previous Revision: [1](https://github.com/apple/swift-evolution/blob/1dcfd35856a6f9c86af2cf7c94a9ab76411739e3/proposals/0120-revise-partition-method.md) ## Introduction This proposal revises the signature for the collection partition algorithm. Partitioning is a foundational API for sorting and for searching through sorted collections. - Swift-evolution thread: [Feedback from standard library team](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160502/016729.html) - Swift Bug: [SR-1965](https://bugs.swift.org/browse/SR-1965) ## Motivation Based on feedback during the review of proposal [SE-0074, Implementation of Binary Search Functions][se-74] and the [list of open issues affecting standard library API stability][list], this is a revised proposal focused only on the existing collection partition method. The standard library's current `partition` methods, which partition a mutable collection using a binary predicate based on the value of the first element of a collection, are used by the standard library's sorting algorithm but don't offer more general partitioning functionality. A more general partition algorithm using a unary (single-argument) predicate would be more flexible and generally useful. [se-74]: 0074-binary-search.md [list]: https://gist.github.com/gribozavr/37e811f12b27c6365fc88e6f9645634d ## Proposed solution The standard library should replace the two existing `partition` methods with a single method taking a unary predicate called `partition(by:)`. `partition(by:)` rearranges the elements of the collection according to the predicate, such that after partitioning there is a pivot index `p` where no element before `p` satisfies the predicate and every element at and after `p` *does* satisfy the predicate. ```swift var n = [30, 40, 20, 30, 30, 60, 10] let p = n.partition(by: { $0 > 30 }) // n == [30, 10, 20, 30, 30, 60, 40] // p == 5 ``` After partitioning is complete, the predicate returns `false` for every element in `n.prefix(upTo: p)` and `true` for every element in `n.suffix(from: p)`. ## Detailed design `partition(by:)` should be added as a `MutableCollection` requirement with default implementations for mutable and bidirectional mutable collections. Any mutable collection can be partitioned, but the bidirectional algorithm generally performs far fewer assignments. The proposed APIs are collected here: ```swift protocol MutableCollection { // existing requirements /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that do /// not match the predicate. /// /// After partitioning a collection, there is a pivot index `p` where /// no element before `p` satisfies the `belongsInSecondPartition` /// predicate and every element at or after `p` satisfies /// `belongsInSecondPartition`. /// /// In the following example, an array of numbers is partitioned by a /// predicate that matches elements greater than 30. /// /// var numbers = [30, 40, 20, 30, 30, 60, 10] /// let p = numbers.partition(by: { $0 > 30 }) /// // p == 5 /// // numbers == [30, 10, 20, 30, 30, 60, 40] /// /// The `numbers` array is now arranged in two partitions. The first /// partition, `numbers.prefix(upTo: p)`, is made up of the elements that /// are not greater than 30. The second partition, `numbers.suffix(from: p)`, /// is made up of the elements that *are* greater than 30. /// /// let first = numbers.prefix(upTo: p) /// // first == [30, 10, 20, 30, 30] /// let second = numbers.suffix(from: p) /// // second == [60, 40] /// /// - Parameter belongsInSecondPartition: A predicate used to partition /// the collection. All elements satisfying this predicate are ordered /// after all elements not satisfying it. /// - Returns: The index of the first element in the reordered collection /// that matches `belongsInSecondPartition`. If no elements in the /// collection match `belongsInSecondPartition`, the returned index is /// equal to the collection's `endIndex`. /// /// - Complexity: O(n) mutating func partition( by belongsInSecondPartition: @noescape (Iterator.Element) throws-> Bool ) rethrows -> Index } extension MutableCollection { mutating func partition( by belongsInSecondPartition: @noescape (Iterator.Element) throws-> Bool ) rethrows -> Index } extension MutableCollection where Self: BidirectionalCollection { mutating func partition( by belongsInSecondPartition: @noescape (Iterator.Element) throws-> Bool ) rethrows -> Index } ``` A full implementation of the two default implementations can be found [in this gist][gist]. [gist]: https://gist.github.com/natecook1000/70f36608ecd6236552ce0e9f79b98cff ## Impact on existing code A thorough, though not exhaustive, search of GitHub for the existing `partition` method found no real evidence of its use. The evident uses of a `partition` method were mainly either tests from the Swift project or third-party implementations similar to the one proposed. Any existing uses of the existing `partition` methods could be flagged or replaced programmatically. The replacement code, on a mutable collection `c`, finding the pivot `p`: ```swift // old let p = c.partition() // new let p = c.first.flatMap({ first in c.partition(by: { $0 >= first }) }) ?? c.startIndex ``` ## Alternatives considered To more closely match the existing API, the `partition(by:)` method could be added only as a default implementation for mutable bidirectional collections. This would unnecessarily limit access to the algorithm for mutable forward collections. The external parameter label could be `where` instead of `by`. However, using `where` implies that the method finds a pre-existing partition point within in the collection (as in `index(where:)`), rather than modifying the collection to be partitioned by the predicate (as in `sort(by:)`, assuming [SE-0118][] is accepted). [SE-0118]: 0118-closure-parameter-names-and-labels.md ---------- [Previous](@previous) | [Next](@next) */
mit