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 |
---|---|---|---|---|---|
MihaiDamian/Dixi | Dixi/Dixi/Extensions/ViewOperators.swift | 1 | 9196 | //
// UIViewOperators.swift
// Dixi
//
// Created by Mihai Damian on 28/02/15.
// Copyright (c) 2015 Mihai Damian. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#else
import AppKit
#endif
/**
Trailing distance to view operator. See also -| (the leading distance operator).
:param: view The constraint's initial view.
:param: constant The trailing/bottom distance.
:returns: A PartialConstraint that specifies the trailing distance to a yet to be defined view. This constraint should be used as an input to the leading distance to view operator.
*/
public func |- <T: CGFloatConvertible> (view: View, constant: T) -> PartialConstraint {
return view |- constant.toCGFloat()
}
/**
Trailing distance to view operator.
:param: view The constraint's initial view.
:param: constant The trailing/bottom distance.
:returns: A PartialConstraint that specifies the trailing distance to a yet to be defined view. This constraint should be used as an input to the leading distance to view operator.
*/
public func |- (view: View, constant: CGFloat) -> PartialConstraint {
return PartialConstraint(secondItem: view, constant: constant)
}
private func sizeConstraintWithView(view: View, #constant: CGFloat, #relation: NSLayoutRelation) -> LayoutConstraint {
var constraint = LayoutConstraint()
constraint.firstItem = view
constraint.firstItemAttribute = .Size
constraint.constant = constant
constraint.relation = relation
return constraint
}
private func sizeConstraintWithLeftView(leftView: View, #rightView: View, #relation: NSLayoutRelation) -> LayoutConstraint {
var constraint = LayoutConstraint()
constraint.firstItem = leftView
constraint.firstItemAttribute = .Size
constraint.relation = relation
constraint.secondItem = rightView
constraint.secondItemAttribute = .Size
return constraint
}
/**
Width greater or equal than constant operator.
:param: view The constraint's view.
:param: constant The width.
:returns: A LayoutConstraint specifying the view's width to be greater than the constant.
*/
public func >= <T: CGFloatConvertible> (view: View, constant: T) -> LayoutConstraint {
return view >= constant.toCGFloat()
}
/**
Width greater or equal than constant operator.
:param: view The constraint's view.
:param: constant The width.
:returns: A LayoutConstraint specifying the view's width to be greater than the constant.
*/
public func >= (view: View, constant: CGFloat) -> LayoutConstraint {
return sizeConstraintWithView(view, constant: constant, relation: .GreaterThanOrEqual)
}
/**
Width greater or equal than view operator.
:param: leftView The first view in the constraint.
:param: rightView The second view in the constraint.
:returns: A LayoutConstraint specifying the first view's width to be greater or equal to the second view's width.
*/
public func >= (leftView: View, rightView: View) -> LayoutConstraint {
return sizeConstraintWithLeftView(leftView, rightView: rightView, relation: .GreaterThanOrEqual)
}
/**
Width smaller or equal than constant operator.
:param: view The constraint's view.
:param: constant The width.
:returns: A LayoutConstraint specifying the view's width to be smaller than the constant.
*/
public func <= <T: CGFloatConvertible> (view: View, constant: T) -> LayoutConstraint {
return view <= constant.toCGFloat()
}
/**
Width smaller or equal than constant operator.
:param: view The constraint's view.
:param: constant The width.
:returns: A LayoutConstraint specifying the view's width to be smaller than the constant.
*/
public func <= (view: View, constant: CGFloat) -> LayoutConstraint {
return sizeConstraintWithView(view, constant: constant, relation: .LessThanOrEqual)
}
/**
Width smaller or equal than view operator.
:param: leftView The first view in the constraint.
:param: rightView The second view in the constraint.
:returns: A LayoutConstraint specifying the first view's width to be smaller or equal to the second view's width.
*/
public func <= (leftView: View, rightView: View) -> LayoutConstraint {
return sizeConstraintWithLeftView(leftView, rightView: rightView, relation: .LessThanOrEqual)
}
/**
Width equal to constant operator.
:param: view The constraint's view.
:param: constant The width.
:returns: A LayoutConstraint specifying the view's width to be equal to a constant.
*/
public func == <T: CGFloatConvertible> (view: View, constant: T) -> LayoutConstraint {
return view == constant.toCGFloat()
}
/**
Width equal to constant operator.
:param: view The constraint's view.
:param: constant The width.
:returns: A LayoutConstraint specifying the view's width to be equal to a constant.
*/
public func == (view: View, constant: CGFloat) -> LayoutConstraint {
return sizeConstraintWithView(view, constant: constant, relation: .Equal)
}
/**
Width equal to view operator.
:param: leftView The first view in the constraint.
:param: rightView The second view in the constraint.
:returns: A LayoutConstraint specifying the first view's width to be equal to the second view's width.
*/
public func == (leftView: View, rightView: View) -> LayoutConstraint {
var constraint = LayoutConstraint()
constraint.firstItem = leftView
constraint.firstItemAttribute = .Size
constraint.relation = .Equal
constraint.secondItem = rightView
constraint.secondItemAttribute = .Size
return constraint
}
/**
Leading distance to superview operator.
:param: constant The leading distance to the superview.
:param: view The view that needs to be distanced from the superview. The view needs to have a superview.
:returns: A LayoutConstraint specifying the leading distance from the view to its superview.
*/
public func |-| <T: CGFloatConvertible> (constant: T, view: View) -> LayoutConstraint {
return constant.toCGFloat() |-| view
}
/**
Leading distance to superview operator.
:param: constant The leading distance to the superview.
:param: view The view that needs to be distanced from the superview. The view needs to have a superview.
:returns: A LayoutConstraint specifying the leading distance from the view to its superview.
*/
public func |-| (constant: CGFloat, view: View) -> LayoutConstraint {
assert(view.superview != nil, "Can't use `distance to superview` operator on view that has no superview")
var constraint = LayoutConstraint()
constraint.firstItem = view
constraint.firstItemAttribute = .LeadingOrTopToSuperview
constraint.relation = .Equal
constraint.secondItem = view.superview!
constraint.secondItemAttribute = .LeadingOrTopToSuperview
constraint.constant = constant
return constraint
}
/**
Trailing distance to superview operator.
:param: view The view that needs to be distanced from the superview. The view needs to have a superview.
:param: constant The trailing distance to the superview.
:returns: A LayoutConstraint specifying the trailing distance from the view to its superview.
*/
public func |-| <T: CGFloatConvertible> (view: View, constant: T) -> LayoutConstraint {
return view |-| constant.toCGFloat()
}
/**
Trailing distance to superview operator.
:param: view The view that needs to be distanced from the superview. The view needs to have a superview.
:param: constant The trailing distance to the superview.
:returns: A LayoutConstraint specifying the trailing distance from the view to its superview.
*/
public func |-| (view: View, constant: CGFloat) -> LayoutConstraint {
assert(view.superview != nil, "Can't use `distance to superview` operator on view that has no superview")
var constraint = LayoutConstraint()
constraint.firstItem = view.superview!
constraint.firstItemAttribute = .TrailingOrBottomToSuperview
constraint.relation = .Equal
constraint.secondItem = view
constraint.secondItemAttribute = .TrailingOrBottomToSuperview
constraint.constant = constant
return constraint
}
/**
Flush views operator.
:param: leftView The first view of the constraint.
:param: rightView The second view of the constraint.
:returns: A LayoutConstraint specifying a distance of 0 points between the two views.
*/
public func || (leftView: View, rightView: View) -> LayoutConstraint {
var constraint = LayoutConstraint()
constraint.firstItem = rightView
constraint.firstItemAttribute = .DistanceToSibling
constraint.relation = .Equal
constraint.secondItem = leftView
constraint.secondItemAttribute = .DistanceToSibling
return constraint
}
/**
Standard distance operator.
:param: leftView The first view of the constraint.
:param: rightView The second view of the constraint.
:returns: A LayoutConstraint specifying a standard (8 points) distance between the two views.
*/
public func - (leftView: View, rightView: View) -> LayoutConstraint {
var constraint = leftView || rightView
constraint.constant = 8
return constraint
}
| mit |
ali-zahedi/AZViewer | AZViewer/AZHeader.swift | 1 | 4313 | //
// AZHeader.swift
// AZViewer
//
// Created by Ali Zahedi on 1/14/1396 AP.
// Copyright © 1396 AP Ali Zahedi. All rights reserved.
//
import Foundation
public enum AZHeaderType {
case title
case success
}
public class AZHeader: AZBaseView{
// MARK: Public
public var title: String = ""{
didSet{
self.titleLabel.text = self.title
}
}
public var type: AZHeaderType! {
didSet{
let hiddenTitle: Bool = self.type == .success ? true : false
self.successButton.isHidden = !hiddenTitle
self.titleLabel.aZConstraints.right?.isActive = false
if hiddenTitle {
_ = self.titleLabel.aZConstraints.right(to: self.successButton, toAttribute: .left,constant: -self.style.sectionGeneralConstant)
}else{
_ = self.titleLabel.aZConstraints.right(constant: -self.style.sectionGeneralConstant)
}
}
}
public var rightButtonTintColor: UIColor! {
didSet{
self.successButton.tintColor = self.rightButtonTintColor
}
}
public var leftButtonTintColor: UIColor! {
didSet{
self.closeButton.tintColor = self.leftButtonTintColor
}
}
// MARK: Internal
internal var delegate: AZPopupViewDelegate?
// MARK: Private
fileprivate var titleLabel: AZLabel = AZLabel()
fileprivate var closeButton: AZButton = AZButton()
fileprivate var successButton: AZButton = AZButton()
// MARK: Override
override init(frame: CGRect) {
super.init(frame: frame)
self.defaultInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.defaultInit()
}
// MARK: Function
fileprivate func defaultInit(){
self.backgroundColor = self.style.sectionHeaderBackgroundColor
for v in [titleLabel, closeButton, successButton] as [UIView]{
v.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(v)
}
// title
self.prepareTitle()
// close button
self.prepareCloseButton()
// success button
self.prepareSuccessButton()
// init
self.type = .title
}
// cancell action
func cancelButtonAction(_ sender: AZButton){
self.delegate?.cancelPopupView()
}
// success action
func successButtonAction(_ sender: AZButton){
self.delegate?.submitPopupView()
}
}
// prepare
extension AZHeader{
// title
fileprivate func prepareTitle(){
_ = self.titleLabel.aZConstraints.parent(parent: self).centerY().right(constant: -self.style.sectionGeneralConstant).left(multiplier: 0.7)
self.titleLabel.textColor = self.style.sectionHeaderTitleColor
self.titleLabel.font = self.style.sectionHeaderTitleFont
}
// close
fileprivate func prepareCloseButton(){
let height = self.style.sectionHeaderHeight * 0.65
_ = self.closeButton.aZConstraints.parent(parent: self).centerY().left(constant: self.style.sectionGeneralConstant).width(constant: height).height(to: self.closeButton, toAttribute: .width)
self.closeButton.setImage(AZAssets.closeImage, for: .normal)
self.closeButton.tintColor = self.style.sectionHeaderLeftButtonTintColor
self.closeButton.addTarget(self, action: #selector(cancelButtonAction(_:)), for: .touchUpInside)
}
// success
fileprivate func prepareSuccessButton(){
let height = self.style.sectionHeaderHeight * 0.65
_ = self.successButton.aZConstraints.parent(parent: self).centerY().right(constant: -self.style.sectionGeneralConstant).width(constant: height).height(to: self.closeButton, toAttribute: .width)
self.successButton.setImage(AZAssets.tickImage, for: .normal)
self.successButton.tintColor = self.style.sectionHeaderRightButtonTintColor
self.successButton.addTarget(self, action: #selector(successButtonAction(_:)), for: .touchUpInside)
}
}
| apache-2.0 |
MenloHacks/ios-app | Menlo Hacks/Pods/Parchment/Parchment/Extensions/UIEdgeInsets.swift | 1 | 160 | import UIKit
extension UIEdgeInsets {
var horizontal: CGFloat {
return left + right
}
var vertical: CGFloat {
return top + bottom
}
}
| mit |
KeithPiTsui/Pavers | Pavers/Pavers.playground/Pages/UIGradientView.xcplaygroundpage/Contents.swift | 2 | 1217 | //: Playground - noun: a place where people can play
import PaversFRP
import PaversUI
import UIKit
import PlaygroundSupport
import Foundation
let colors = [UIColor.random.cgColor, UIColor.random.cgColor, UIColor.random.cgColor]
let locations = [NSNumber(value: 0),NSNumber(value: 0.25),NSNumber(value: 0.5)]
let sp = CGPoint(x: 0, y: 0)
let ep = CGPoint(x: 1, y: 1)
let gViewStyle =
UIGradientView.lens.gradientLayer.colors .~ colors
>>> UIGradientView.lens.gradientLayer.locations .~ locations
>>> UIGradientView.lens.gradientLayer.startPoint .~ sp
>>> UIGradientView.lens.gradientLayer.endPoint .~ ep
>>> UIGradientView.lens.frame .~ frame
let gView = UIGradientView()
gView |> gViewStyle
//PlaygroundPage.current.liveView = gView
// Set the device type and orientation.
let (parent, _) = playgroundControllers(device: .phone5_5inch, orientation: .portrait)
// Render the screen.
let frame = parent.view.frame
PlaygroundPage.current.liveView = gView
Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { _ in
let colors = [UIColor.random.cgColor, UIColor.random.cgColor, UIColor.random.cgColor]
gView |> UIGradientView.lens.gradientLayer.colors .~ colors
}
| mit |
XCEssentials/UniFlow | Sources/7_ExternalBindings/ExternalBindingBDD_ThenContext.swift | 1 | 2581 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich (maxim@khatskevi.ch)
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 Combine
//---
public
extension ExternalBindingBDD
{
struct ThenContext<W: SomeMutationDecriptor, G> // W - When, G - Given
{
public
let description: String
//internal
let given: (Dispatcher, W) throws -> G?
public
func then(
scope: String = #file,
location: Int = #line,
_ then: @escaping (Dispatcher, G) -> Void
) -> ExternalBinding {
.init(
description: description,
scope: scope,
context: S.self,
location: location,
given: given,
then: then
)
}
public
func then(
scope: String = #file,
location: Int = #line,
_ noDispatcherHandler: @escaping (G) -> Void
) -> ExternalBinding {
then(scope: scope, location: location) { _, input in
noDispatcherHandler(input)
}
}
public
func then(
scope: String = #file,
location: Int = #line,
_ sourceOnlyHandler: @escaping () -> Void
) -> ExternalBinding where G == Void {
then(scope: scope, location: location) { _, _ in
sourceOnlyHandler()
}
}
}
}
| mit |
codespy/HashingUtility | Hashing Utility/Hmac.swift | 1 | 3617 | // The MIT License (MIT)
//
// Copyright (c) 2015 Krzysztof Rossa
//
// 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
// inspired by http://stackoverflow.com/a/24411522
enum HMACAlgorithm {
case MD5, SHA1, SHA224, SHA256, SHA384, SHA512
func toCCHmacAlgorithm() -> CCHmacAlgorithm {
var result: Int = 0
switch self {
case .MD5:
result = kCCHmacAlgMD5
case .SHA1:
result = kCCHmacAlgSHA1
case .SHA224:
result = kCCHmacAlgSHA224
case .SHA256:
result = kCCHmacAlgSHA256
case .SHA384:
result = kCCHmacAlgSHA384
case .SHA512:
result = kCCHmacAlgSHA512
}
return CCHmacAlgorithm(result)
}
func digestLength() -> Int {
var result: CInt = 0
switch self {
case .MD5:
result = CC_MD5_DIGEST_LENGTH
case .SHA1:
result = CC_SHA1_DIGEST_LENGTH
case .SHA224:
result = CC_SHA224_DIGEST_LENGTH
case .SHA256:
result = CC_SHA256_DIGEST_LENGTH
case .SHA384:
result = CC_SHA384_DIGEST_LENGTH
case .SHA512:
result = CC_SHA512_DIGEST_LENGTH
}
return Int(result)
}
}
extension String {
func calculateHash(algorithm: HMACAlgorithm) -> String! {
//let encodig = NSUTF8StringEncoding
let encodig = NSUTF8StringEncoding
let str = self.cStringUsingEncoding(encodig)
let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(encodig))
let digestLen = algorithm.digestLength()
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
switch (algorithm) {
case HMACAlgorithm.MD5:
CC_MD5(str!, strLen, result)
case HMACAlgorithm.SHA1:
CC_SHA1(str!, strLen, result)
case HMACAlgorithm.SHA224:
CC_SHA224(str!, strLen, result)
case HMACAlgorithm.SHA256:
CC_SHA256(str!, strLen, result)
case HMACAlgorithm.SHA384:
CC_SHA384(str!, strLen, result)
case HMACAlgorithm.SHA512:
CC_SHA512(str!, strLen, result)
}
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(hash)
}
}
| mit |
AHuaner/Gank | Gank/Class/Home/AHHomeWebViewController.swift | 1 | 7521 | //
// AHHomeWebViewController.swift
// Gank
//
// Created by AHuaner on 2017/1/7.
// Copyright © 2017年 CoderAhuan. All rights reserved.
//
import UIKit
class AHHomeWebViewController: BaseWebViewController {
// MARK: - property
var gankModel: GankModel?
// 文章是否被收藏
fileprivate var isCollected: Bool = false
// MARK: - control
// 弹窗
fileprivate lazy var moreView: AHMoreView = {
let moreView = AHMoreView.moreView()
let W = kScreen_W / 2
let H = CGFloat(moreView.titles.count * 44 + 15)
moreView.alpha = 0.01
moreView.frame = CGRect(x: kScreen_W - W - 3, y: 50, width: W, height: H)
return moreView
}()
// 蒙版
fileprivate var maskBtnView: UIButton = {
let maskBtnView = UIButton()
maskBtnView.frame = kScreen_BOUNDS
maskBtnView.backgroundColor = UIColor.clear
return maskBtnView
}()
// MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.statusBarStyle = .lightContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - event && methods
fileprivate func setupUI() {
self.title = "加载中..."
let oriImage = UIImage(named: "icon_more")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
navigationItem.rightBarButtonItem = UIBarButtonItem(image: oriImage, style: .plain, target: self, action: #selector(moreClick))
maskBtnView.addTarget(self, action: #selector(dismissMoreView), for: .touchUpInside)
moreView.tableViewdidSelectClouse = { [unowned self] (indexPath) in
self.dismissMoreView()
switch indexPath.row {
case 0: // 收藏
self.collectGankAction()
case 1: // 分享
self.shareEvent()
case 2: // 复制链接
let pasteboard = UIPasteboard.general
pasteboard.string = self.urlString!
ToolKit.showSuccess(withStatus: "复制成功")
case 3: // Safari打开
guard let urlString = self.urlString else { return }
guard let url = URL(string: urlString) else { return }
UIApplication.shared.openURL(url)
default: break
}
}
}
// 检验文章是否已被收藏
fileprivate func cheakIsCollected() {
let query: BmobQuery = BmobQuery(className: "Collect")
let array = [["userId": User.info?.objectId], ["gankId": gankModel?.id]]
query.addTheConstraintByAndOperation(with: array)
query.findObjectsInBackground { (array, error) in
// 加载失败
if error != nil { return }
guard let ganksArr = array else { return }
if ganksArr.count == 1 { // 以收藏
self.moreView.gankBe(collected: true)
self.isCollected = true
self.gankModel?.objectId = (ganksArr.first as! BmobObject).objectId
} else { // 未收藏
self.moreView.gankBe(collected: false)
self.isCollected = false
self.gankModel?.objectId = nil
}
guard let nav = self.navigationController else { return }
nav.view.insertSubview(self.maskBtnView, aboveSubview: self.webView)
nav.view.insertSubview(self.moreView, aboveSubview: self.webView)
UIView.animate(withDuration: 0.25) {
self.moreView.alpha = 1
}
}
}
func moreClick() {
cheakIsCollected()
}
func dismissMoreView() {
maskBtnView.removeFromSuperview()
UIView.animate(withDuration: 0.25, animations: {
self.moreView.alpha = 0.01
}) { (_) in
self.moreView.removeFromSuperview()
}
}
// 点击收藏
fileprivate func collectGankAction() {
if User.info == nil { // 未登录
let loginVC = AHLoginViewController()
let nav = UINavigationController(rootViewController: loginVC)
present(nav, animated: true, completion: nil)
return
}
// 检验用户是否在其他设备登录
ToolKit.checkUserLoginedWithOtherDevice(noLogin: {
// 登录状态
// 取消收藏
if self.isCollected {
ToolKit.show(withStatus: "正在取消收藏")
guard let objectId = self.gankModel?.objectId else { return }
let gank: BmobObject = BmobObject(outDataWithClassName: "Collect", objectId: objectId)
gank.deleteInBackground { (isSuccessful, error) in
if isSuccessful { // 删除成功
ToolKit.showSuccess(withStatus: "已取消收藏")
self.isCollected = false
self.moreView.gankBe(collected: false)
} else {
AHLog(error!)
ToolKit.showError(withStatus: "取消收藏失败")
}
}
return
}
// 收藏
let gankInfo = BmobObject(className: "Collect")
gankInfo?.setObject(User.info!.objectId, forKey: "userId")
gankInfo?.setObject(User.info!.mobilePhoneNumber, forKey: "userPhone")
if let gankModel = self.gankModel {
gankInfo?.setObject(gankModel.id, forKey: "gankId")
gankInfo?.setObject(gankModel.desc, forKey: "gankDesc")
gankInfo?.setObject(gankModel.type, forKey: "gankType")
gankInfo?.setObject(gankModel.user, forKey: "gankUser")
gankInfo?.setObject(gankModel.publishedAt, forKey: "gankPublishAt")
gankInfo?.setObject(gankModel.url, forKey: "gankUrl")
}
gankInfo?.saveInBackground(resultBlock: { (isSuccessful, error) in
if error != nil { // 收藏失败
AHLog(error!)
ToolKit.showError(withStatus: "收藏失败")
} else { // 收藏成功
ToolKit.showSuccess(withStatus: "收藏成功")
self.isCollected = true
self.moreView.gankBe(collected: true)
}
})
})
}
fileprivate func shareEvent() {
UMSocialUIManager.showShareMenuViewInWindow { (platformType, userInfo) in
let messageObject = UMSocialMessageObject()
let shareObject = UMShareWebpageObject.shareObject(withTitle: Bundle.appName, descr: self.gankModel?.desc, thumImage: UIImage(named: "icon108"))
shareObject?.webpageUrl = self.gankModel?.url
messageObject.shareObject = shareObject
UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: self) { (data, error) in
if error == nil {
AHLog(data)
} else {
AHLog("分享失败\(error!)")
}
}
}
}
}
| mit |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Controllers/Drawing/DrawingBrushColorViewModel.swift | 1 | 1325 | //
// DrawingBrushColorViewModel.swift
// Rocket.Chat
//
// Created by Artur Rymarz on 12.02.2018.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
final class DrawingBrushColorViewModel {
internal let cellIdentifier = "DrawingBrushColorCell"
internal var selectedColorLabel: String {
return localized("chat.drawing.settings.color.selected")
}
internal var othersLabel: String {
return localized("chat.drawing.settings.color.others")
}
internal let availableColors: [UIColor] = [
.black,
.darkGray,
.lightGray,
.gray,
.red,
.green,
.blue,
.cyan,
.yellow,
.magenta,
.orange,
.purple,
.brown,
// custom
UIColor(hex: "#FFC0CB"),
UIColor(hex: "#008080"),
UIColor(hex: "#FFE4E1"),
UIColor(hex: "#FFD700"),
UIColor(hex: "#D3FFCE"),
UIColor(hex: "#FF7373"),
UIColor(hex: "#40E0D0"),
UIColor(hex: "#E6E6FA"),
UIColor(hex: "#B0E0E6"),
UIColor(hex: "#C6E2FF"),
UIColor(hex: "#003366"),
UIColor(hex: "#800080"),
UIColor(hex: "#347CA0"),
UIColor(hex: "#C7CA24"),
UIColor(hex: "#FD91A0"),
UIColor(hex: "#F9AF91")
]
}
| mit |
emilstahl/swift | validation-test/compiler_crashers/26950-swift-constraints-constraintsystem-solve.swift | 9 | 262 | // RUN: not --crash %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{class T{struct
c{class d<T:T.h
| apache-2.0 |
A-Kod/vkrypt | Pods/SwiftyVK/Library/Sources/Extensions/OperationConvertible.swift | 2 | 217 | public protocol OperationConvertible {
func toOperation() -> Operation
func cancel()
}
extension OperationConvertible where Self: Operation {
func toOperation() -> Operation {
return self
}
}
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/27206-llvm-foldingset-swift-classtype-nodeequals.swift | 1 | 470 | // 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
func b{{
class B
}
class B<T where H:a{
class b{
class B
let:{
let:B=b{
| apache-2.0 |
ben-ng/swift | test/IRGen/generic_class_anyobject.swift | 4 | 464 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=i386_or_x86_64
// REQUIRES: objc_interop
func foo<T: AnyObject>(_ x: T) -> T { return x }
// CHECK-LABEL: define hidden %objc_object* @_TF23generic_class_anyobject3barFPs9AnyObject_PS0__(%objc_object*)
// CHECK: call %objc_object* @_TF23generic_class_anyobject3foo
func bar(_ x: AnyObject) -> AnyObject { return foo(x) }
| apache-2.0 |
LeonardoCardoso/InfiniteBlocks | iOS/InfiniteBlocks/InfiniteBlocksTests/InfiniteBlocksTests.swift | 1 | 923 | //
// InfiniteBlocksTests.swift
// InfiniteBlocksTests
//
// Created by Leonardo Cardoso on 7/21/15.
// Copyright (c) 2015 leocardz. All rights reserved.
//
import UIKit
import XCTest
class InfiniteBlocksTests: 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.
}
}
}
| apache-2.0 |
kareman/SwiftShell | Sources/SwiftShell/Context.swift | 1 | 5042 | /*
* Released under the MIT License (MIT), http://opensource.org/licenses/MIT
*
* Copyright (c) 2015 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com)
*
*/
import Foundation
public protocol Context: CustomDebugStringConvertible {
var env: [String: String] { get set }
var stdin: ReadableStream { get set }
var stdout: WritableStream { get set }
var stderror: WritableStream { get set }
/**
The current working directory.
Must be used instead of `run("cd", "...")` because all the `run` commands are executed in a
separate process and changing the directory there will not affect the rest of the Swift script.
*/
var currentdirectory: String { get set }
}
extension Context {
/** A textual representation of this instance, suitable for debugging. */
public var debugDescription: String {
var result = ""
debugPrint("stdin:", stdin, "stdout:", stdout, "stderror:", stderror, "currentdirectory:", currentdirectory, to: &result)
debugPrint("env:", env, to: &result)
return result
}
}
public struct CustomContext: Context, CommandRunning {
public var env: [String: String]
public var stdin: ReadableStream
public var stdout: WritableStream
public var stderror: WritableStream
/**
The current working directory.
Must be used instead of `run("cd", "...")` because all the `run` commands are executed in a
separate process and changing the directory there will not affect the rest of the Swift script.
*/
public var currentdirectory: String
/** Creates a blank CustomContext where env and stdin are empty, stdout and stderror discard everything and
currentdirectory is the current working directory. */
public init() {
let encoding = String.Encoding.utf8
env = [String: String]()
stdin = FileHandleStream(FileHandle.nullDevice, encoding: encoding)
stdout = FileHandleStream(FileHandle.nullDevice, encoding: encoding)
stderror = FileHandleStream(FileHandle.nullDevice, encoding: encoding)
currentdirectory = main.currentdirectory
}
/** Creates an identical copy of another Context. */
public init(_ context: Context) {
env = context.env
stdin = context.stdin
stdout = context.stdout
stderror = context.stderror
currentdirectory = context.currentdirectory
}
}
private func createTempdirectory() -> String {
let name = URL(fileURLWithPath: main.path).lastPathComponent
let tempdirectory = URL(fileURLWithPath: NSTemporaryDirectory()) + (name + "-" + ProcessInfo.processInfo.globallyUniqueString)
do {
try Files.createDirectory(atPath: tempdirectory.path, withIntermediateDirectories: true, attributes: nil)
return tempdirectory.path + "/"
} catch let error as NSError {
exit(errormessage: "Could not create new temporary directory '\(tempdirectory)':\n\(error.localizedDescription)", errorcode: error.code)
} catch {
exit(errormessage: "Unexpected error: \(error)")
}
}
extension CommandLine {
/** Workaround for nil crash in CommandLine.arguments when run in Xcode. */
static var safeArguments: [String] {
self.argc == 0 ? [] : self.arguments
}
}
public final class MainContext: Context, CommandRunning {
/// The default character encoding used throughout SwiftShell.
/// Only affects stdin, stdout and stderror if they have not been used yet.
public var encoding = String.Encoding.utf8 // TODO: get encoding from environmental variable LC_CTYPE.
public lazy var env = ProcessInfo.processInfo.environment as [String: String]
public lazy var stdin: ReadableStream = {
FileHandleStream(FileHandle.standardInput, encoding: self.encoding)
}()
public lazy var stdout: WritableStream = {
let stdout = StdoutStream.default
stdout.encoding = self.encoding
return stdout
}()
public lazy var stderror: WritableStream = {
FileHandleStream(FileHandle.standardError, encoding: self.encoding)
}()
/**
The current working directory.
Must be used instead of `run("cd", "...")` because all the `run` commands are executed in
separate processes and changing the directory there will not affect the rest of the Swift script.
This directory is also used as the base for relative URLs.
*/
public var currentdirectory: String {
get { return Files.currentDirectoryPath + "/" }
set {
if !Files.changeCurrentDirectoryPath(newValue) {
exit(errormessage: "Could not change the working directory to \(newValue)")
}
}
}
/**
The tempdirectory is unique each time a script is run and is created the first time it is used.
It lies in the user's temporary directory and will be automatically deleted at some point.
*/
public private(set) lazy var tempdirectory: String = createTempdirectory()
/** The arguments this executable was launched with. Use main.path to get the path. */
public private(set) lazy var arguments: [String] = Array(CommandLine.safeArguments.dropFirst())
/** The path to the currently running executable. Will be empty in playgrounds. */
public private(set) lazy var path: String = CommandLine.safeArguments.first ?? ""
fileprivate init() {}
}
public let main = MainContext()
| mit |
Chan4iOS/SCMapCatch-Swift | SCMapCatch-Swift/UserDefaults+MC.swift | 1 | 5345 |
// UserDefault+MC.swift
// SCMapCatch-Swift_Demo
//
// Created by 陈世翰 on 17/4/17.
// Copyright © 2017年 Coder Chan. All rights reserved.
//
import Foundation
extension UserDefaults{
/*
UserDefaults set object by level keys , it will auto choose to create elements on the path if the elements on the path have not been created,or delete the element on the path when the param 'object' is nil
:mObject:object to insert
:keys:path components
:warning:The first obj in keys must be 'Stirng' type ,otherwise it will return nil
*/
func mc_set<T:Hashable>(object mObject:Any?,forKeys keys:Array<T>){
guard keys.count>0 else {
return
}
guard keys.first != nil else{
return
}
let firstKey = keys.first as? String//第一个key必须为string userDefault规定
guard firstKey != nil else{
return
}
if keys.count==1{
mc_set(object: mObject, forkey: firstKey!)
}else{
let tree = value(forKey:firstKey!)
var mDict = [T : Any]()
if tree != nil {
guard tree is [T:Any] else {
return
}
mDict = tree as! [T : Any]
}
var inputKeys = keys
inputKeys.remove(at: 0)
let rootTree = mc_handleTree(tree: mDict, components: inputKeys , obj: mObject)
guard rootTree != nil else {
return
}
set(rootTree!, forKey: firstKey!)
}
synchronize();
}
/*
UserDefaults set object by level keys , it will auto choose to create elements on the path if the elements on the path have not been created,or delete the element on the path when the param 'object' is nil
:mObject:object to insert
:keys:path components
:warning:The first obj in keys must be 'Stirng' type ,otherwise it will return nil
*/
func mc_set<T:Hashable>(object mObject:Any?,forKeys keys:T...){
mc_set(object: mObject, forKeys: keys)
}
/*
UserDefaults set object key , it will auto choose to create element when the param 'object' != nil,or delete the element on the path when the param 'object' is nil
:mObject:object to insert
:key:String
*/
func mc_set(object:Any?,forkey key:String){
if object != nil{
set(object!, forKey: key)
}else{
removeObject(forKey:key)
}
synchronize();
}
/*Recursive traversal func
:param:tree this level tree
:param:components the rest of path components
:return:hanle result of this level
*/
fileprivate func mc_handleTree<T:Hashable>(tree: [T:Any],components:Array<T>,obj:Any?)->Dictionary<T, Any>?{
var result = tree
if components.count==1{//last level
result = result.mc_set(value: obj, forkey: components.first!)
}else{//middle level
var nextComponents = components
nextComponents.remove(at: 0)
let nextTree = tree[components.first!]
if nextTree != nil && nextTree is [T : Any]{
result[components.first!] = mc_handleTree(tree:nextTree as! [T : Any], components:nextComponents , obj: obj)
}else{
result[components.first!] = mc_handleTree(tree:[T : Any](), components:nextComponents , obj: obj)
}
}
return result
}
class func mc_set(object:Any?,forkey key:String){
self.standard.mc_set(object: object, forkey: key)
}
class func mc_set<T:Hashable>(object mObject:Any?,forKeys keys:T...){
self.standard.mc_set(object: mObject, forKeys: keys)
}
class func mc_set<T:Hashable>(object mObject:Any?,forKeys keys:Array<T>){
self.standard.mc_set(object: mObject, forKeys: keys)
}
/*get object by path
:param:keys path components
:return:result
:warning:the first object of keys must be 'String' type , otherwise it will return nil
*/
func mc_object<T:Hashable>(forKeys keys:T...) -> Any? {
return mc_object(forKeys: keys)
}
/*get object by path
:param:keys path components
:return:result
:warning:the first object of keys must be 'String' type , otherwise it will return nil
*/
func mc_object<T:Hashable>(forKeys keys:Array<T>) -> Any? {
guard keys.count>0 else{
return nil
}
let firstKey = keys.first as? String
guard firstKey != nil else{
return nil
}
if keys.count == 1{
return object(forKey: firstKey!)
}else{
let nextLevel = object(forKey: firstKey!)
guard nextLevel != nil && nextLevel is Dictionary<T,Any> else{
return nil
}
var nextLevelKeys = keys
nextLevelKeys.remove(at: 0)
return (nextLevel as! Dictionary<T,Any>).mc_object(forKeys: nextLevelKeys)
}
}
class func mc_object<T:Hashable>(forKeys keys:T...) -> Any? {
return self.standard.mc_object(forKeys: keys)
}
class func mc_object<T:Hashable>(forKeys keys:Array<T>) -> Any? {
return self.standard.mc_object(forKeys: keys)
}
}
| mit |
piv199/LocalisysChat | LocalisysChat/Sources/Modules/Common/Chat/Components/LocalisysChatToolbarView.swift | 1 | 2699 | //
// ToolbarView.swift
// LocalisysChat
//
// Created by Olexii Pyvovarov on 6/26/17.
// Copyright © 2017 Olexii Pyvovarov. All rights reserved.
//
import UIKit
final class LocalisysChatToolbarView: UIView {
// MARK: - UI
internal lazy var textArea: AutoTextView = ChatTextInputArea()
internal var actionButtons: [ChatActionButton] = []
internal lazy var sendButton: ChatSendButton = ChatSendButton()
// MARK: - Properties
fileprivate var isInWriteMode: Bool { return !textArea.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
// MARK: - Lifecycle
override init(frame: CGRect = .zero) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
fileprivate func setupUI() {
backgroundColor = .clear
[[textArea, sendButton], actionButtons].flatten().forEach(addSubview)
}
// MARK: - Actions
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
[[sendButton], actionButtons].flatten().forEach { (view: UIView) in view.sizeToFit() }
var currentMaxX = bounds.width - 24.0
let minHeight: CGFloat = 44.0
if isInWriteMode || actionButtons.count == 0 {
currentMaxX -= sendButton.bounds.width
sendButton.frame = CGRect(origin: .init(x: bounds.width - 24.0 - sendButton.bounds.width,
y: (bounds.height - minHeight) + (minHeight - sendButton.bounds.height) / 2.0),
size: sendButton.bounds.size)
actionButtons.forEach { $0.isHidden = true }
sendButton.isHidden = false
currentMaxX -= 12.0
// sendButton.isEnabled = isInWriteMode
} else {
for additionButton in actionButtons {
currentMaxX -= additionButton.bounds.width
additionButton.frame = CGRect(x: currentMaxX,
y: (bounds.height - minHeight) + (minHeight - additionButton.bounds.height) / 2.0,
width: additionButton.bounds.width,
height: additionButton.bounds.height)
currentMaxX -= 12.0
}
sendButton.isHidden = true
actionButtons.forEach { $0.isHidden = false }
}
let textAreaWidth = currentMaxX - 24.0
let textAreaHeight = textArea.expectedHeight
textArea.frame = CGRect(x: 24.0, y: (bounds.height - textAreaHeight) / 2.0,
width: textAreaWidth, height: textAreaHeight)
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return .init(width: size.width, height: max(min(textArea.expectedHeight, size.height), 44.0))
}
}
| unlicense |
cplaverty/KeitaiWaniKani | WaniKaniKit/Database/Table/KanjiTable.swift | 1 | 1231 | //
// KanjiTable.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
final class KanjiTable: Table, SubjectTable {
let id = Column(name: "id", type: .int, nullable: false, primaryKey: true)
let createdAt = Column(name: "created_at", type: .float, nullable: false)
let level = Column(name: "level", type: .int, nullable: false)
let slug = Column(name: "slug", type: .text, nullable: false)
let hiddenAt = Column(name: "hidden_at", type: .float)
let documentURL = Column(name: "document_url", type: .text, nullable: false)
let characters = Column(name: "characters", type: .text, nullable: false)
let meaningMnemonic = Column(name: "meaning_mnemonic", type: .text, nullable: false)
let meaningHint = Column(name: "meaning_hint", type: .text, nullable: true)
let readingMnemonic = Column(name: "reading_mnemonic", type: .text, nullable: false)
let readingHint = Column(name: "reading_hint", type: .text, nullable: true)
let lessonPosition = Column(name: "lesson_position", type: .int, nullable: false)
init() {
super.init(name: "kanji",
indexes: [TableIndex(name: "idx_kanji_by_level", columns: [level])])
}
}
| mit |
hedjirog/QiitaFeed | Pods/ReactiveCocoa/ReactiveCocoa/Swift/Atomic.swift | 1 | 1653 |
//
// Atomic.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-06-10.
// Copyright (c) 2014 GitHub. All rights reserved.
//
/// An atomic variable.
internal final class Atomic<T> {
private var spinlock = OS_SPINLOCK_INIT
private var _value: T
/// Atomically gets or sets the value of the variable.
var value: T {
get {
lock()
let v = _value
unlock()
return v
}
set(newValue) {
lock()
_value = newValue
unlock()
}
}
/// Initializes the variable with the given initial value.
init(_ value: T) {
_value = value
}
private func lock() {
withUnsafeMutablePointer(&spinlock, OSSpinLockLock)
}
private func unlock() {
withUnsafeMutablePointer(&spinlock, OSSpinLockUnlock)
}
/// Atomically replaces the contents of the variable.
///
/// Returns the old value.
func swap(newValue: T) -> T {
return modify { _ in newValue }
}
/// Atomically modifies the variable.
///
/// Returns the old value.
func modify(action: T -> T) -> T {
let (oldValue, _) = modify { oldValue in (action(oldValue), 0) }
return oldValue
}
/// Atomically modifies the variable.
///
/// Returns the old value, plus arbitrary user-defined data.
func modify<U>(action: T -> (T, U)) -> (T, U) {
lock()
let oldValue: T = _value
let (newValue, data) = action(_value)
_value = newValue
unlock()
return (oldValue, data)
}
/// Atomically performs an arbitrary action using the current value of the
/// variable.
///
/// Returns the result of the action.
func withValue<U>(action: T -> U) -> U {
lock()
let result = action(_value)
unlock()
return result
}
}
| mit |
tbergmen/TableViewModel | Example/Tests/SampleCell2.swift | 1 | 1199 | /*
Copyright (c) 2016 Tunca Bergmen <tunca@bergmen.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
import UIKit
class SampleCell2: UITableViewCell {
@IBOutlet weak var button: UIButton!
}
| mit |
nearfri/Strix | Tests/StrixTests/Core/ParserTests.swift | 1 | 5291 | import XCTest
@testable import Strix
private enum Seed {
static let state1: ParserState = .init(stream: "123456")
static let state2: ParserState = state1.withStream(state1.stream.dropFirst())
static let intErrors: [ParseError] = [.expected(label: "integer")]
static let strErrors: [ParseError] = [.expected(label: "string")]
static let intSuccessParser: Parser<Int> = .init({ _ in .success(1, intErrors, state2) })
static let intFailureParser: Parser<Int> = .init({ _ in .failure(intErrors, state2) })
static let strSuccessParser: Parser<String> = .init({ _ in .success("wow", strErrors, state2) })
static let strFailureParser: Parser<String> = .init({ _ in .failure(strErrors, state2) })
}
private class TextOutput: TextOutputStream {
var text: String = ""
func write(_ string: String) {
text += string
}
}
final class ParserTests: XCTestCase {
func test_map_success_success() {
// Given
let parser = Seed.strSuccessParser
// When
let mappedParser = parser.map({ $0 })
let reply = mappedParser.parse(Seed.state1)
// Then
XCTAssertEqual(reply.result.value, "wow")
}
func test_map_failure_failure() {
// Given
let parser = Seed.strFailureParser
// When
let mappedParser = parser.map({ $0 })
let reply = mappedParser.parse(Seed.state1)
// Then
XCTAssertNil(reply.result.value)
}
func test_mapWithSubstring_success_success() {
// Given
let parser = Seed.strSuccessParser
var substr: Substring = ""
// When
let mappedParser = parser.map { v, str -> String in
substr = str
return v
}
let reply = mappedParser.parse(Seed.state1)
// Then
XCTAssertEqual(reply.result.value, "wow")
XCTAssertEqual(substr, "1")
}
func test_mapWithSubstring_failure_failure() {
// Given
let parser = Seed.strFailureParser
// When
let mappedParser: Parser<Substring> = parser.map({ $1 })
let reply = mappedParser.parse(Seed.state1)
// Then
XCTAssertNil(reply.result.value)
}
func test_flatMap_successAndSuccess_success() {
// Given
let parser = Seed.intSuccessParser
// When
let mappedParser = parser.flatMap({ _ in Seed.strSuccessParser })
let reply = mappedParser.parse(Seed.state1)
// Then
XCTAssertEqual(reply.result.value, "wow")
}
func test_flatMap_successAndFailure_failure() {
// Given
let parser = Seed.intSuccessParser
// When
let mappedParser = parser.flatMap({ _ in Seed.strFailureParser })
let reply = mappedParser.parse(Seed.state1)
// Then
XCTAssertNil(reply.result.value)
}
func test_flatMap_failureAndSuccess_failure() {
// Given
let parser = Seed.intFailureParser
// When
let mappedParser = parser.flatMap({ _ in Seed.strSuccessParser })
let reply = mappedParser.parse(Seed.state1)
// Then
XCTAssertNil(reply.result.value)
}
func test_flatMapWithSubstring_successAndSuccess_success() {
// Given
let parser = Seed.intSuccessParser
var substr: Substring = ""
// When
let mappedParser = parser.flatMap { _, str -> Parser<String> in
substr = str
return Seed.strSuccessParser
}
let reply = mappedParser.parse(Seed.state1)
// Then
XCTAssertEqual(reply.result.value, "wow")
XCTAssertEqual(substr, "1")
}
func test_print() {
// Given
let parser = Seed.intSuccessParser
let textOutput = TextOutput()
// When
let printableParser = parser.print("int number", to: textOutput)
_ = printableParser.parse(Seed.state1)
// Then
XCTAssertEqual(textOutput.text, """
(1:1:"1"): int number: enter
(1:2:"2"): int number: leave: success(1, [expected(label: "integer")])
""")
}
func test_run_success() throws {
// Given
let parser = Seed.intSuccessParser
// When, then
XCTAssertNoThrow(try parser.run("123456"))
}
func test_run_failure() {
// Given
let input = "hello"
let errors: [ParseError] = Seed.intErrors
let parser: Parser<Int> = .init { state in
return .failure(errors, state.withStream(state.stream.dropFirst()))
}
// When
XCTAssertThrowsError(try parser.run(input)) { error in
guard let runError = error as? RunError else {
XCTFail("Invalid error type: \(type(of: error))")
return
}
// Then
XCTAssertEqual(runError.input, input)
XCTAssertEqual(runError.position, input.index(after: input.startIndex))
XCTAssertEqual(runError.underlyingErrors, errors)
}
}
}
| mit |
hacktoolkit/htk-ios-Twitter | Twitter/AppDelegate.swift | 1 | 3058 | //
// AppDelegate.swift
// Twitter
//
// Created by Jonathan Tsai on 9/26/14.
// Copyright (c) 2014 Hacktoolkit. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var storyboard = UIStoryboard(name: "Main", bundle: nil)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "userDidLogout", name: TWITTER_USER_DID_LOGOUT_NOTIFICATION, object: nil)
if TwitterUser.currentUser != nil {
// Go to the logged in screen
NSLog("Current user detected: \(TwitterUser.currentUser?.name)")
var vc = storyboard.instantiateViewControllerWithIdentifier("TwitterNavigationController") as UIViewController
window?.rootViewController = vc
}
return true
}
func userDidLogout() {
var vc = storyboard.instantiateInitialViewController() as UIViewController
window?.rootViewController = vc
}
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:.
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
TwitterClient.sharedInstance.openURL(url)
return true
}
}
| mit |
srn214/Floral | Floral/Pods/CLImagePickerTool/CLImagePickerTool/CLImagePickerTool/AnotherPickView/CLImagePickerAnotherViewController.swift | 2 | 7276 | //
// CLImagePickerAnotherViewController.swift
// CLImagePickerTool
//
// Created by darren on 2017/11/17.
// Copyright © 2017年 陈亮陈亮. All rights reserved.
//
import UIKit
import Photos
class CLImagePickerAnotherViewController: UIViewController {
@IBOutlet weak var sureBtn: UIButton!
@IBOutlet weak var cancelBtn: UIButton!
@IBOutlet weak var resetBtn: UIButton!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var bottomHYS: NSLayoutConstraint!
@objc let imageCellID = "imagecellID"
// 是否隐藏视频文件,默认不隐藏
@objc public var isHiddenVideo: Bool = false
// 是否隐藏图片文件,显示视频文件,默认不隐藏
@objc public var isHiddenImage: Bool = false
// 视频和照片只能选择一种,不能同时选择,默认可以同时选择
@objc var onlyChooseImageOrVideo: Bool = false
@objc var photoArr: [CLImagePickerPhotoModel]?
var MaxImagesCount: Int = 0
@objc var singleChooseImageCompleteClouse: CLImagePickerSingleChooseImageCompleteClouse?
override func viewDidLoad() {
super.viewDidLoad()
self.initView()
self.bottomHYS.constant = UIDevice.current.isX() == true ? 50 + 34:50
CLNotificationCenter.addObserver(self, selector: #selector(CLImagePickerAnotherViewController.PreviewForSelectOrNotSelectedNoticFunc), name: NSNotification.Name(rawValue:PreviewForSelectOrNotSelectedNotic), object: nil)
}
deinit {
CLNotificationCenter.removeObserver(self)
}
@objc func PreviewForSelectOrNotSelectedNoticFunc(notic:Notification) {
let modelPreView = notic.object as! PreviewModel
for model in (self.photoArr ?? []) {
if model.phAsset == modelPreView.phAsset {
model.isSelect = modelPreView.isCheck
}
}
if CLPickersTools.instence.getSavePictureCount() > 0 {
let title = "\(sureStr)(\(CLPickersTools.instence.getSavePictureCount()))"
self.sureBtn.setTitle(title, for: .normal)
self.sureBtn.isEnabled = true
self.resetBtn.isEnabled = true
} else {
self.sureBtn.isEnabled = false
self.resetBtn.isEnabled = false
}
self.collectionView.reloadData()
}
func initView() {
// 存储用户设置的最多图片数量
UserDefaults.standard.set(MaxImagesCount, forKey: CLImagePickerMaxImagesCount)
UserDefaults.standard.synchronize()
CLPickersTools.instence.isHiddenVideo = isHiddenVideo // 是否隐藏视频文件赋值
CLPickersTools.instence.isHiddenImage = isHiddenImage
// 清除保存的数据
CLPickersTools.instence.clearPicture()
// 如果用户之前设置的是onlyChooseImageOrVideo类型,记得将这个类型刚开始就置空
UserDefaults.standard.set(0, forKey: UserChooserType)
UserDefaults.standard.synchronize()
self.resetBtn.setTitle(resetStr, for: .normal)
self.sureBtn.setTitle(sureStr, for: .normal)
self.cancelBtn.setTitle(cancelStr, for: .normal)
if CLPickersTools.instence.getSavePictureCount() > 0 {
let title = "\(sureStr)(\(CLPickersTools.instence.getSavePictureCount()))"
self.sureBtn.setTitle(title, for: .normal)
self.sureBtn.isEnabled = true
self.resetBtn.isEnabled = true
} else {
self.sureBtn.isEnabled = false
self.resetBtn.isEnabled = false
}
let flowout = UICollectionViewFlowLayout.init()
self.collectionView.collectionViewLayout = flowout
flowout.scrollDirection = .horizontal
flowout.minimumInteritemSpacing = 10
self.collectionView.register(UINib.init(nibName: "ImagePickerChooseImageCellV2", bundle: BundleUtil.getCurrentBundle()), forCellWithReuseIdentifier: imageCellID)
self.photoArr = CLPickersTools.instence.loadPhotoForAll().first?.values.first?.reversed()
self.collectionView.reloadData()
}
@IBAction func clickSureBtn(_ sender: Any) {
self.dismiss(animated: true) {
if self.singleChooseImageCompleteClouse != nil {
self.singleChooseImageCompleteClouse!(CLPickersTools.instence.getChoosePictureArray(),nil)
}
}
}
@IBAction func clickResetBtn(_ sender: Any) {
if self.photoArr != nil {
for model in self.photoArr! {
model.isSelect = false
}
}
CLPickersTools.instence.clearPicture()
self.resetBtn.isEnabled = false
self.sureBtn.isEnabled = false
self.sureBtn.setTitle(sureStr, for: .normal)
if self.onlyChooseImageOrVideo {
for model in (self.photoArr ?? []) {
model.onlyChooseImageOrVideo = false
}
// 重置选择的类型
UserDefaults.standard.set(0, forKey: UserChooserType)
UserDefaults.standard.synchronize()
}
self.collectionView.reloadData()
}
@IBAction func clickCancelBtn(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func clickEditorBtn(_ sender: Any) {
}
@IBAction func clickPhotoBtn(_ sender: Any) {
}
}
extension CLImagePickerAnotherViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photoArr?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let model = self.photoArr?[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imageCellID, for: indexPath) as! ImagePickerChooseImageCellV2
cell.onlyChooseImageOrVideo = self.onlyChooseImageOrVideo
cell.model = model
cell.imagePickerChooseImage = {[weak self] () in
let chooseCount = CLPickersTools.instence.getSavePictureCount()
if chooseCount == 0 {
self?.sureBtn.setTitle(sureStr, for: .normal)
self?.sureBtn.isEnabled = false
self?.resetBtn.isEnabled = false
} else {
self?.sureBtn.setTitle("\(sureStr)(\(chooseCount))", for: .normal)
self?.sureBtn.isEnabled = true
self?.resetBtn.isEnabled = true
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout:UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let model = self.photoArr![indexPath.row]
var W: CGFloat = (CGFloat(model.phAsset?.pixelWidth ?? 0))
let H: CGFloat = CGFloat(model.phAsset?.pixelHeight ?? 0)
if W / H < 1 {
W = KScreenWidth/3.2
} else {
W = KScreenWidth/1.2
}
return CGSize(width: W, height: 230)
}
}
| mit |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/BinaryDelimited.swift | 4 | 8486 | // Sources/SwiftProtobuf/BinaryDelimited.swift - Delimited support
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Helpers to read/write message with a length prefix.
///
// -----------------------------------------------------------------------------
import Foundation
/// Helper methods for reading/writing messages with a length prefix.
public enum BinaryDelimited {
/// Additional errors for delimited message handing.
public enum Error: Swift.Error {
/// If a read/write to the stream fails, but the stream's `streamError` is nil,
/// this error will be throw instead since the stream didn't provide anything
/// more specific. A common cause for this can be failing to open the stream
/// before trying to read/write to it.
case unknownStreamError
/// While reading/writing to the stream, less than the expected bytes was
/// read/written.
case truncated
}
/// Serialize a single size-delimited message from the given stream. Delimited
/// format allows a single file or stream to contain multiple messages,
/// whereas normally writing multiple non-delimited messages to the same
/// stream would cause them to be merged. A delimited message is a varint
/// encoding the message size followed by a message of exactly that size.
///
/// - Parameters:
/// - message: The message to be written.
/// - to: The `OutputStream` to write the message to. The stream is
/// is assumed to be ready to be written to.
/// - partial: If `false` (the default), this method will check
/// `Message.isInitialized` before encoding to verify that all required
/// fields are present. If any are missing, this method throws
/// `BinaryEncodingError.missingRequiredFields`.
/// - Throws: `BinaryEncodingError` if encoding fails, throws
/// `BinaryDelimited.Error` for some writing errors, or the
/// underlying `OutputStream.streamError` for a stream error.
public static func serialize(
message: Message,
to stream: OutputStream,
partial: Bool = false
) throws {
// TODO: Revisit to avoid the extra buffering when encoding is streamed in general.
let serialized = try message.serializedData(partial: partial)
let totalSize = Varint.encodedSize(of: UInt64(serialized.count)) + serialized.count
var data = Data(count: totalSize)
data.withUnsafeMutableBytes { (pointer: UnsafeMutablePointer<UInt8>) in
var encoder = BinaryEncoder(forWritingInto: pointer)
encoder.putBytesValue(value: serialized)
}
var written: Int = 0
data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in
written = stream.write(pointer, maxLength: totalSize)
}
if written != totalSize {
if written == -1 {
if let streamError = stream.streamError {
throw streamError
}
throw BinaryDelimited.Error.unknownStreamError
}
throw BinaryDelimited.Error.truncated
}
}
/// Reads a single size-delimited message from the given stream. Delimited
/// format allows a single file or stream to contain multiple messages,
/// whereas normally parsing consumes the entire input. A delimited message
/// is a varint encoding the message size followed by a message of exactly
/// exactly that size.
///
/// - Parameters:
/// - messageType: The type of message to read.
/// - from: The `InputStream` to read the data from. The stream is assumed
/// to be ready to read from.
/// - extensions: An `ExtensionMap` used to look up and decode any
/// extensions in this message or messages nested within this message's
/// fields.
/// - partial: If `false` (the default), this method will check
/// `Message.isInitialized` before encoding to verify that all required
/// fields are present. If any are missing, this method throws
/// `BinaryEncodingError.missingRequiredFields`.
/// - options: The BinaryDecodingOptions to use.
/// - Returns: The message read.
/// - Throws: `BinaryDecodingError` if decoding fails, throws
/// `BinaryDelimited.Error` for some reading errors, and the
/// underlying InputStream.streamError for a stream error.
public static func parse<M: Message>(
messageType: M.Type,
from stream: InputStream,
extensions: ExtensionMap? = nil,
partial: Bool = false,
options: BinaryDecodingOptions = BinaryDecodingOptions()
) throws -> M {
var message = M()
try merge(into: &message,
from: stream,
extensions: extensions,
partial: partial,
options: options)
return message
}
/// Updates the message by reading a single size-delimited message from
/// the given stream. Delimited format allows a single file or stream to
/// contain multiple messages, whereas normally parsing consumes the entire
/// input. A delimited message is a varint encoding the message size
/// followed by a message of exactly that size.
///
/// - Note: If this method throws an error, the message may still have been
/// partially mutated by the binary data that was decoded before the error
/// occurred.
///
/// - Parameters:
/// - mergingTo: The message to merge the data into.
/// - from: The `InputStream` to read the data from. The stream is assumed
/// to be ready to read from.
/// - extensions: An `ExtensionMap` used to look up and decode any
/// extensions in this message or messages nested within this message's
/// fields.
/// - partial: If `false` (the default), this method will check
/// `Message.isInitialized` before encoding to verify that all required
/// fields are present. If any are missing, this method throws
/// `BinaryEncodingError.missingRequiredFields`.
/// - options: The BinaryDecodingOptions to use.
/// - Throws: `BinaryDecodingError` if decoding fails, throws
/// `BinaryDelimited.Error` for some reading errors, and the
/// underlying InputStream.streamError for a stream error.
public static func merge<M: Message>(
into message: inout M,
from stream: InputStream,
extensions: ExtensionMap? = nil,
partial: Bool = false,
options: BinaryDecodingOptions = BinaryDecodingOptions()
) throws {
let length = try Int(decodeVarint(stream))
if length == 0 {
// The message was all defaults, nothing to actually read.
return
}
var data = Data(count: length)
var bytesRead: Int = 0
data.withUnsafeMutableBytes { (pointer: UnsafeMutablePointer<UInt8>) in
bytesRead = stream.read(pointer, maxLength: length)
}
if bytesRead != length {
if bytesRead == -1 {
if let streamError = stream.streamError {
throw streamError
}
throw BinaryDelimited.Error.unknownStreamError
}
throw BinaryDelimited.Error.truncated
}
try message.merge(serializedData: data,
extensions: extensions,
partial: partial,
options: options)
}
}
// TODO: This should go away when encoding/decoding are more stream based
// as that should provide a more direct way to do this. This is basically
// a rewrite of BinaryDecoder.decodeVarint().
internal func decodeVarint(_ stream: InputStream) throws -> UInt64 {
// Buffer to reuse within nextByte.
var readBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
defer { readBuffer.deallocate(capacity: 1) }
func nextByte() throws -> UInt8 {
let bytesRead = stream.read(readBuffer, maxLength: 1)
if bytesRead != 1 {
if bytesRead == -1 {
if let streamError = stream.streamError {
throw streamError
}
throw BinaryDelimited.Error.unknownStreamError
}
throw BinaryDelimited.Error.truncated
}
return readBuffer[0]
}
var value: UInt64 = 0
var shift: UInt64 = 0
while true {
let c = try nextByte()
value |= UInt64(c & 0x7f) << shift
if c & 0x80 == 0 {
return value
}
shift += 7
if shift > 63 {
throw BinaryDecodingError.malformedProtobuf
}
}
}
| mit |
zhfish/XMMediator | XMMediator/Categories/ModuleA/XMMediator+A.swift | 1 | 610 | //
// XMMediator+A.swift
// XMMediator
//
// Created by 王晨 on 2017/3/5.
// Copyright © 2017年 天星宿命. All rights reserved.
//
import UIKit
extension XMMediator {
func A_viewController() -> UIViewController {
let vc = performWith(targetName: "A", actionName: "viewController", params: nil, shouldCacheTarget: false) as! UIViewController
return vc
}
func A_badge(with fake:Int) -> Int {
let result = performWith(targetName: "A", actionName: "badge", params: ["fake":String(fake)], shouldCacheTarget: false) as! Int
return result
}
}
| mit |
swiftcodex/Swift-Radio-Pro | SwiftRadio/Libraries/Spring/SpringAnimation.swift | 4 | 3757 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To (meng@designcode.io)
//
// 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
@objc public class SpringAnimation: NSObject {
public class func spring(duration: TimeInterval, animations: @escaping () -> Void) {
UIView.animate(
withDuration: duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: [],
animations: {
animations()
},
completion: nil
)
}
public class func springEaseIn(duration: TimeInterval, animations: (() -> Void)!) {
UIView.animate(
withDuration: duration,
delay: 0,
options: .curveEaseIn,
animations: {
animations()
},
completion: nil
)
}
public class func springEaseOut(duration: TimeInterval, animations: (() -> Void)!) {
UIView.animate(
withDuration: duration,
delay: 0,
options: .curveEaseOut,
animations: {
animations()
}, completion: nil
)
}
public class func springEaseInOut(duration: TimeInterval, animations: (() -> Void)!) {
UIView.animate(
withDuration: duration,
delay: 0,
options: UIView.AnimationOptions(),
animations: {
animations()
}, completion: nil
)
}
public class func springLinear(duration: TimeInterval, animations: (() -> Void)!) {
UIView.animate(
withDuration: duration,
delay: 0,
options: .curveLinear,
animations: {
animations()
}, completion: nil
)
}
public class func springWithDelay(duration: TimeInterval, delay: TimeInterval, animations: (() -> Void)!) {
UIView.animate(
withDuration: duration,
delay: delay,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: [],
animations: {
animations()
}, completion: nil
)
}
public class func springWithCompletion(duration: TimeInterval, animations: (() -> Void)!, completion: ((Bool) -> Void)!) {
UIView.animate(
withDuration: duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: [],
animations: {
animations()
}, completion: { finished in
completion(finished)
}
)
}
}
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/09020-swift-parser-parsedeclstruct.swift | 11 | 310 | // 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 a( ) -> {
{
}
struct d<T where T: a {
struct g<g : e {
class B {
{
}
func a( ) {
{
}
{
}
struct A {
{
}
protocol A {
{
}
{
{
}
}
struct
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/05807-llvm-foldingset-swift-normalprotocolconformance-getnodeprofile.swift | 11 | 232 | // 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<{class A{{{}}class A{class A{struct d{class b{func a<b:a | mit |
VaclavLustek/VLFramework | Pod/Classes/View/Table/Cells/VLBaseCell.swift | 1 | 2283 | //
// VLBaseCell.swift
// Pods
//
// Created by Václav Luštěk.
//
//
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Import
import UIKit
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Settings
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Constants
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Class
public class VLBaseCell: UITableViewCell {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
@IBOutlet private weak var titleLabel: UILabel!
public var titleText: String? = nil {
didSet {
self.titleLabel.text = titleText
}
}
@IBOutlet private weak var subtitleLabel: UILabel!
public var subtitleText: String? = nil {
didSet {
self.subtitleLabel.text = subtitleText
}
}
@IBOutlet private weak var mainIV: UIImageView!
public var mainImage: UIImage? = nil {
didSet {
self.mainIV.image = mainImage;
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Layout
public override var bounds: CGRect {
didSet {
self.contentView.bounds = bounds
}
}
public override func layoutSubviews() {
super.layoutSubviews()
self.contentView.setNeedsUpdateConstraints()
self.contentView.updateConstraintsIfNeeded()
self.contentView.setNeedsLayout()
self.contentView.layoutIfNeeded()
if let titleLabel: UILabel = self.titleLabel {
titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(titleLabel.bounds)
}
if let subtitleLabel: UILabel = self.subtitleLabel {
subtitleLabel.preferredMaxLayoutWidth = CGRectGetWidth(subtitleLabel.bounds)
}
}
}
| mit |
svdo/swift-SecurityExtensions | SecurityExtensionsTests/SecKey+KeychainTests.swift | 1 | 1060 | // Copyright (c) 2016 Stefan van den Oord. All rights reserved.
import Quick
import Nimble
import SecurityExtensions
class SecKey_KeychainTests: QuickSpec {
override func spec() {
it("can return the keychain tag of a key") {
let keys = testKeyPair()
expect(keys.privateKey.keychainTag) != ""
expect(keys.publicKey.keychainTag) != ""
}
it("can retrieve a key by tag") {
let keys = testKeyPair()
let privTag = keys.privateKey.keychainTag
let pubTag = keys.publicKey.keychainTag
expect(privTag).toNot(beNil())
expect(pubTag).toNot(beNil())
if let privTag = privTag, let pubTag = pubTag {
let retrievedPrivKey = SecKey.loadFromKeychain(tag: privTag)
let retrievedPubKey = SecKey.loadFromKeychain(tag: pubTag)
expect(retrievedPrivKey?.keyData) == keys.privateKey.keyData
expect(retrievedPubKey?.keyData) == keys.publicKey.keyData
}
}
}
}
| mit |
Vadim-Yelagin/DataSource | DataSourceTests/CompositeDataSourceTests.swift | 1 | 1003 | //
// CompositeDataSourceTests.swift
// DataSourceTests
//
// Created by Aleksei Bobrov on 06/02/2019.
// Copyright © 2019 Fueled. All rights reserved.
//
import DataSource
import Nimble
import Quick
class CompositeDataSourceTests: QuickSpecWithDataSets {
override func spec() {
var dataSource: CompositeDataSource!
var staticDataSources: [StaticDataSource<Int>]!
beforeEach {
let firstStaticDataSource = StaticDataSource(sections: [DataSourceSection(items: self.testDataSet, supplementaryItems: self.supplementaryItemOfKind)])
let secondStaticDataSource = StaticDataSource(sections: [DataSourceSection(items: self.testDataSet2)])
staticDataSources = [firstStaticDataSource, secondStaticDataSource]
dataSource = CompositeDataSource(staticDataSources)
}
itBehavesLike("DataSource protocol") { ["DataSource": dataSource!, "InitialData": [self.testDataSet, self.testDataSet2], "LeafDataSource": staticDataSources!, "SupplementaryItems": [self.supplementaryItemOfKind]] }
}
}
| mit |
kickstarter/ios-oss | Library/EnvironmentTests.swift | 1 | 365 | @testable import Library
import XCTest
final class EnvironmentTests: XCTestCase {
func testInit() {
let env = Environment()
XCTAssertEqual(env.calendar, Calendar.current)
XCTAssertEqual(env.language, Language(languageStrings: Locale.preferredLanguages))
XCTAssertEqual(env.locale, Locale.current)
XCTAssertEqual(env.countryCode, "US")
}
}
| apache-2.0 |
kickstarter/ios-oss | Library/ViewModels/ManagePledgeViewModel.swift | 1 | 21169 | import KsApi
import Prelude
import ReactiveExtensions
import ReactiveSwift
public typealias ManagePledgeViewParamConfigData = (
projectParam: Param,
backingParam: Param?
)
public enum ManagePledgeAlertAction: CaseIterable {
case updatePledge
case changePaymentMethod
case chooseAnotherReward
case contactCreator
case cancelPledge
case viewRewards
}
public protocol ManagePledgeViewModelInputs {
func beginRefresh()
func configureWith(_ params: ManagePledgeViewParamConfigData)
func cancelPledgeDidFinish(with message: String)
func fixButtonTapped()
func menuButtonTapped()
func menuOptionSelected(with action: ManagePledgeAlertAction)
func pledgeViewControllerDidUpdatePledgeWithMessage(_ message: String)
func viewDidLoad()
}
public protocol ManagePledgeViewModelOutputs {
var configurePaymentMethodView: Signal<ManagePledgePaymentMethodViewData, Never> { get }
var configurePledgeSummaryView: Signal<ManagePledgeSummaryViewData, Never> { get }
var configureRewardReceivedWithData: Signal<ManageViewPledgeRewardReceivedViewData, Never> { get }
var endRefreshing: Signal<Void, Never> { get }
var goToCancelPledge: Signal<CancelPledgeViewData, Never> { get }
var goToChangePaymentMethod: Signal<PledgeViewData, Never> { get }
var goToContactCreator: Signal<(MessageSubject, KSRAnalytics.MessageDialogContext), Never> { get }
var goToFixPaymentMethod: Signal<PledgeViewData, Never> { get }
var goToRewards: Signal<Project, Never> { get }
var goToUpdatePledge: Signal<PledgeViewData, Never> { get }
var loadProjectAndRewardsIntoDataSource: Signal<(Project, [Reward]), Never> { get }
var loadPullToRefreshHeaderView: Signal<(), Never> { get }
var notifyDelegateManagePledgeViewControllerFinishedWithMessage: Signal<String?, Never> { get }
var paymentMethodViewHidden: Signal<Bool, Never> { get }
var pledgeDetailsSectionLabelText: Signal<String, Never> { get }
var pledgeDisclaimerViewHidden: Signal<Bool, Never> { get }
var rewardReceivedViewControllerViewIsHidden: Signal<Bool, Never> { get }
var rightBarButtonItemHidden: Signal<Bool, Never> { get }
var showActionSheetMenuWithOptions: Signal<[ManagePledgeAlertAction], Never> { get }
var showErrorBannerWithMessage: Signal<String, Never> { get }
var showSuccessBannerWithMessage: Signal<String, Never> { get }
var startRefreshing: Signal<(), Never> { get }
var title: Signal<String, Never> { get }
}
public protocol ManagePledgeViewModelType {
var inputs: ManagePledgeViewModelInputs { get }
var outputs: ManagePledgeViewModelOutputs { get }
}
public final class ManagePledgeViewModel:
ManagePledgeViewModelType, ManagePledgeViewModelInputs, ManagePledgeViewModelOutputs {
public init() {
let params = Signal.combineLatest(
self.configureWithProjectOrParamSignal,
self.viewDidLoadSignal
)
.map(first)
let projectParam = params.map(first)
let shouldBeginRefresh = Signal.merge(
self.pledgeViewControllerDidUpdatePledgeWithMessageSignal.ignoreValues(),
self.beginRefreshSignal
)
// Keep track of whether the project has successfully loaded at least once.
let projectLoaded = MutableProperty<Bool>(false)
let shouldFetchProjectWithParam = Signal.merge(
projectParam,
projectParam.takeWhen(shouldBeginRefresh)
)
let fetchProjectEvent = shouldFetchProjectWithParam
// Only fetch the project if it hasn't yet succeeded, to avoid this call occurring with each refresh.
.filter { [projectLoaded] _ in projectLoaded.value == false }
.switchMap { param in
AppEnvironment.current.apiService.fetchProject(param: param)
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
.switchMap { project in
fetchProjectRewards(project: project)
}
.materialize()
}
let initialProject = fetchProjectEvent.values()
// Once we know we have a project value, keep track of that.
.on(value: { [projectLoaded] _ in projectLoaded.value = true })
let backingParamFromConfigData = params.map(second)
.skipNil()
let backingParamFromProject = initialProject.map { $0.personalization.backing?.id }
.skipNil()
.map(Param.id)
let backingParam = Signal.merge(
backingParamFromConfigData,
backingParamFromProject
.take(until: backingParamFromConfigData.ignoreValues())
)
let shouldFetchGraphBackingWithParam = Signal.merge(
backingParam,
backingParam.takeWhen(shouldBeginRefresh)
)
let graphBackingEvent = shouldFetchGraphBackingWithParam
.map { param in param.id }
.skipNil()
.switchMap { backingId in
AppEnvironment.current.apiService
.fetchBacking(id: backingId, withStoredCards: false)
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
.materialize()
}
let graphBackingProject = graphBackingEvent.values()
.map { $0.project }
let graphBackingEnvelope = graphBackingEvent.values()
let backing = graphBackingEnvelope
.map { $0.backing }
let endRefreshingWhenProjectFailed = fetchProjectEvent.errors()
.ignoreValues()
let endRefreshingWhenBackingCompleted = graphBackingEvent
.filter { $0.isTerminating }
.ksr_delay(.milliseconds(300), on: AppEnvironment.current.scheduler)
.ignoreValues()
self.endRefreshing = Signal.merge(
endRefreshingWhenProjectFailed,
endRefreshingWhenBackingCompleted
)
.ignoreValues()
let project = initialProject.combineLatest(with: backing)
.map { project, backing -> Project in
/**
Here we are updating the `Project`'s `Backing` with an updated one from GraphQL.
This is because, at the time of writing, v1 does not return add-ons or bonus amount but GraphQL does.
*/
let p = (project |> Project.lens.personalization.backing .~ backing)
return p
}
let userIsCreatorOfProject = project.map { project in
currentUserIsCreator(of: project)
}
let projectAndReward = Signal.combineLatest(project, backing)
.compactMap { project, backing -> (Project, Reward)? in
guard let reward = backing.reward else { return (project, .noReward) }
return (project, reward)
}
self.title = graphBackingProject.combineLatest(with: userIsCreatorOfProject)
.map(navigationBarTitle(with:userIsCreatorOfProject:))
self.configurePaymentMethodView = backing.map(managePledgePaymentMethodViewData)
self.configurePledgeSummaryView = Signal.combineLatest(projectAndReward, backing)
.map(unpack)
.compactMap(managePledgeSummaryViewData)
let projectOrBackingFailedToLoad = Signal.merge(
fetchProjectEvent.map { $0.error as Error? },
graphBackingEvent.map { $0.error as Error? }
)
.filter(isNotNil)
self.loadPullToRefreshHeaderView = projectOrBackingFailedToLoad
.take(until: backing.ignoreValues())
.ignoreValues()
self.paymentMethodViewHidden = Signal.combineLatest(
userIsCreatorOfProject,
backing.map { backing in backing.paymentSource }
)
.map { userIsCreatorOfProject, creditCard in userIsCreatorOfProject || creditCard == nil }
.skipRepeats()
self.loadProjectAndRewardsIntoDataSource = projectAndReward.combineLatest(with: backing)
.map(unpack)
.map { project, reward, backing -> (Project, [Reward]) in
(project, distinctRewards([reward] + (backing.addOns ?? [])))
}
self.rightBarButtonItemHidden = Signal.merge(
params.mapConst(true),
self.loadPullToRefreshHeaderView.mapConst(true),
self.loadProjectAndRewardsIntoDataSource.mapConst(false)
)
.skipRepeats()
self.pledgeDisclaimerViewHidden = Signal.combineLatest(
self.loadProjectAndRewardsIntoDataSource,
userIsCreatorOfProject
)
.map(unpack)
.map { _, rewards, userIsCreatorOfProject in
rewards.map { $0.estimatedDeliveryOn }.allSatisfy(isNil) || userIsCreatorOfProject
}
self.pledgeDetailsSectionLabelText = userIsCreatorOfProject.map {
$0 ? Strings.Pledge_details() : Strings.Your_pledge_details()
}
self.startRefreshing = Signal.merge(
params.ignoreValues(),
shouldBeginRefresh.ignoreValues()
)
let latestRewardDeliveryDate = self.loadProjectAndRewardsIntoDataSource.map { _, rewards in
rewards
.compactMap { $0.estimatedDeliveryOn }
.reduce(0) { accum, value in max(accum, value) }
}
self.configureRewardReceivedWithData = Signal.combineLatest(project, backing, latestRewardDeliveryDate)
.map { project, backing, latestRewardDeliveryDate in
ManageViewPledgeRewardReceivedViewData(
project: project,
backerCompleted: backing.backerCompleted ?? false,
estimatedDeliveryOn: latestRewardDeliveryDate,
backingState: backing.status
)
}
let menuOptions = Signal.combineLatest(project, backing, userIsCreatorOfProject)
.map(actionSheetMenuOptionsFor(project:backing:userIsCreatorOfProject:))
self.showActionSheetMenuWithOptions = menuOptions
.takeWhen(self.menuButtonTappedSignal)
let backedRewards = self.loadProjectAndRewardsIntoDataSource.map(second)
self.goToUpdatePledge = Signal.combineLatest(project, backing, backedRewards)
.takeWhen(self.menuOptionSelectedSignal.filter { $0 == .updatePledge })
.map { project, backing, rewards in (project, backing, rewards, .update) }
.map(pledgeViewData)
self.goToRewards = project
.takeWhen(self.menuOptionSelectedSignal.filter { $0 == .chooseAnotherReward || $0 == .viewRewards })
let cancelPledgeSelected = self.menuOptionSelectedSignal
.filter { $0 == .cancelPledge }
.ignoreValues()
self.goToCancelPledge = Signal.combineLatest(project, backing)
.takeWhen(cancelPledgeSelected)
.filter { _, backing in backing.cancelable }
.map(cancelPledgeViewData(with:backing:))
self.goToContactCreator = project
.takeWhen(self.menuOptionSelectedSignal.filter { $0 == .contactCreator })
.map { project in (MessageSubject.project(project), .backerModal) }
self.goToChangePaymentMethod = Signal.combineLatest(project, backing, backedRewards)
.takeWhen(self.menuOptionSelectedSignal.filter { $0 == .changePaymentMethod })
.map { project, backing, rewards in
(project, backing, rewards, .changePaymentMethod)
}
.map(pledgeViewData)
self.goToFixPaymentMethod = Signal.combineLatest(project, backing, backedRewards)
.takeWhen(self.fixButtonTappedSignal)
.map { project, backing, rewards in
(project, backing, rewards, .fixPaymentMethod)
}
.map(pledgeViewData)
self.notifyDelegateManagePledgeViewControllerFinishedWithMessage = Signal.merge(
self.cancelPledgeDidFinishWithMessageProperty.signal,
backing.skip(first: 1).mapConst(nil)
)
self.rewardReceivedViewControllerViewIsHidden = latestRewardDeliveryDate.map { $0 == 0 }
self.showSuccessBannerWithMessage = self.pledgeViewControllerDidUpdatePledgeWithMessageSignal
let cancelBackingDisallowed = backing
.map { $0.cancelable }
.filter(isFalse)
let attemptedDisallowedCancelBackingMessage = cancelBackingDisallowed
.takeWhen(cancelPledgeSelected)
.map { _ in
// swiftformat:disable wrap
Strings.We_dont_allow_cancelations_that_will_cause_a_project_to_fall_short_of_its_goal_within_the_last_24_hours()
// swiftformat:enable wrap
}
let networkErrorMessage = Signal.merge(
fetchProjectEvent.errors().ignoreValues(),
graphBackingEvent.errors().ignoreValues()
)
.map { _ in Strings.Something_went_wrong_please_try_again() }
self.showErrorBannerWithMessage = Signal.merge(
attemptedDisallowedCancelBackingMessage,
networkErrorMessage
)
// Tracking
Signal.zip(self.loadProjectAndRewardsIntoDataSource, backing)
.map(unpack)
.observeValues { project, rewards, backing in
guard let reward = backing.reward else { return }
let checkoutData = checkoutProperties(
from: project,
baseReward: reward,
addOnRewards: rewards,
selectedQuantities: selectedRewardQuantities(in: backing),
additionalPledgeAmount: backing.bonusAmount,
pledgeTotal: backing.amount,
shippingTotal: Double(backing.shippingAmount ?? 0),
isApplePay: backing.paymentSource?.paymentType == .applePay
)
AppEnvironment.current.ksrAnalytics.trackManagePledgePageViewed(
project: project,
reward: reward,
checkoutData: checkoutData
)
}
}
private let (beginRefreshSignal, beginRefreshObserver) = Signal<Void, Never>.pipe()
public func beginRefresh() {
self.beginRefreshObserver.send(value: ())
}
private let (configureWithProjectOrParamSignal, configureWithProjectOrParamObserver)
= Signal<ManagePledgeViewParamConfigData, Never>.pipe()
public func configureWith(_ params: ManagePledgeViewParamConfigData) {
self.configureWithProjectOrParamObserver.send(value: params)
}
private let cancelPledgeDidFinishWithMessageProperty = MutableProperty<String?>(nil)
public func cancelPledgeDidFinish(with message: String) {
self.cancelPledgeDidFinishWithMessageProperty.value = message
}
private let (fixButtonTappedSignal, fixButtonTappedObserver) = Signal<Void, Never>.pipe()
public func fixButtonTapped() {
self.fixButtonTappedObserver.send(value: ())
}
private let (menuButtonTappedSignal, menuButtonTappedObserver) = Signal<Void, Never>.pipe()
public func menuButtonTapped() {
self.menuButtonTappedObserver.send(value: ())
}
private let (menuOptionSelectedSignal, menuOptionSelectedObserver) = Signal<ManagePledgeAlertAction, Never>
.pipe()
public func menuOptionSelected(with action: ManagePledgeAlertAction) {
self.menuOptionSelectedObserver.send(value: action)
}
private let (
pledgeViewControllerDidUpdatePledgeWithMessageSignal,
pledgeViewControllerDidUpdatePledgeWithMessageObserver
) = Signal<String, Never>.pipe()
public func pledgeViewControllerDidUpdatePledgeWithMessage(_ message: String) {
self.pledgeViewControllerDidUpdatePledgeWithMessageObserver.send(value: message)
}
private let (viewDidLoadSignal, viewDidLoadObserver) = Signal<(), Never>.pipe()
public func viewDidLoad() {
self.viewDidLoadObserver.send(value: ())
}
public let configurePaymentMethodView: Signal<ManagePledgePaymentMethodViewData, Never>
public let configurePledgeSummaryView: Signal<ManagePledgeSummaryViewData, Never>
public let configureRewardReceivedWithData: Signal<ManageViewPledgeRewardReceivedViewData, Never>
public let endRefreshing: Signal<Void, Never>
public let goToCancelPledge: Signal<CancelPledgeViewData, Never>
public let goToChangePaymentMethod: Signal<PledgeViewData, Never>
public let goToContactCreator: Signal<(MessageSubject, KSRAnalytics.MessageDialogContext), Never>
public let goToFixPaymentMethod: Signal<PledgeViewData, Never>
public let goToRewards: Signal<Project, Never>
public let goToUpdatePledge: Signal<PledgeViewData, Never>
public let loadProjectAndRewardsIntoDataSource: Signal<(Project, [Reward]), Never>
public let loadPullToRefreshHeaderView: Signal<(), Never>
public let paymentMethodViewHidden: Signal<Bool, Never>
public let pledgeDetailsSectionLabelText: Signal<String, Never>
public let pledgeDisclaimerViewHidden: Signal<Bool, Never>
public let notifyDelegateManagePledgeViewControllerFinishedWithMessage: Signal<String?, Never>
public let rewardReceivedViewControllerViewIsHidden: Signal<Bool, Never>
public let rightBarButtonItemHidden: Signal<Bool, Never>
public let showActionSheetMenuWithOptions: Signal<[ManagePledgeAlertAction], Never>
public let showSuccessBannerWithMessage: Signal<String, Never>
public let showErrorBannerWithMessage: Signal<String, Never>
public let startRefreshing: Signal<(), Never>
public let title: Signal<String, Never>
public var inputs: ManagePledgeViewModelInputs { return self }
public var outputs: ManagePledgeViewModelOutputs { return self }
}
// MARK: - Functions
private func fetchProjectRewards(project: Project) -> SignalProducer<Project, ErrorEnvelope> {
return AppEnvironment.current.apiService
.fetchProjectRewards(projectId: project.id)
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
.switchMap { projectRewards -> SignalProducer<Project, ErrorEnvelope> in
var allRewards = projectRewards
if let noRewardReward = project.rewardData.rewards.first {
allRewards.insert(noRewardReward, at: 0)
}
let projectWithBackingAndRewards = project
|> Project.lens.rewardData.rewards .~ allRewards
return SignalProducer(value: projectWithBackingAndRewards)
}
}
private func pledgeViewData(
project: Project,
backing: Backing,
rewards: [Reward],
context: PledgeViewContext
) -> PledgeViewData {
return PledgeViewData(
project: project,
rewards: rewards,
selectedQuantities: selectedRewardQuantities(in: backing),
selectedLocationId: backing.locationId,
refTag: nil,
context: context
)
}
private func actionSheetMenuOptionsFor(
project: Project,
backing: Backing,
userIsCreatorOfProject: Bool
) -> [ManagePledgeAlertAction] {
if userIsCreatorOfProject {
return [.viewRewards]
}
guard project.state == .live else {
return [.viewRewards, .contactCreator]
}
if backing.status == .preauth {
return [.contactCreator]
}
return ManagePledgeAlertAction.allCases.filter { $0 != .viewRewards }
}
private func navigationBarTitle(
with project: Project,
userIsCreatorOfProject: Bool
) -> String {
if userIsCreatorOfProject {
return Strings.Pledge_details()
}
return project.state == .live ? Strings.Manage_your_pledge() : Strings.Your_pledge()
}
private func managePledgeMenuCTAType(for managePledgeAlertAction: ManagePledgeAlertAction)
-> KSRAnalytics.ManagePledgeMenuCTAType {
switch managePledgeAlertAction {
case .cancelPledge: return .cancelPledge
case .changePaymentMethod: return .changePaymentMethod
case .chooseAnotherReward: return .chooseAnotherReward
case .contactCreator: return .contactCreator
case .updatePledge: return .updatePledge
case .viewRewards: return .viewRewards
}
}
private func cancelPledgeViewData(
with project: Project,
backing: Backing
) -> CancelPledgeViewData {
return .init(
project: project,
projectName: project.name,
omitUSCurrencyCode: project.stats.omitUSCurrencyCode,
backingId: backing.graphID,
pledgeAmount: backing.amount
)
}
private func managePledgePaymentMethodViewData(
with backing: Backing
) -> ManagePledgePaymentMethodViewData {
ManagePledgePaymentMethodViewData(
backingState: backing.status,
expirationDate: backing.paymentSource?.expirationDate,
lastFour: backing.paymentSource?.lastFour,
creditCardType: backing.paymentSource?.type,
paymentType: backing.paymentSource?.paymentType
)
}
private func managePledgeSummaryViewData(
with project: Project,
backedReward: Reward,
backing: Backing
) -> ManagePledgeSummaryViewData? {
guard let backer = backing.backer else { return nil }
let isRewardLocalPickup = isRewardLocalPickup(backing.reward)
let projectCurrencyCountry = projectCountry(forCurrency: project.stats.currency) ?? project.country
return ManagePledgeSummaryViewData(
backerId: backer.id,
backerName: backer.name,
backerSequence: backing.sequence,
backingState: backing.status,
bonusAmount: backing.bonusAmount,
currentUserIsCreatorOfProject: currentUserIsCreator(of: project),
isNoReward: backedReward.id == Reward.noReward.id,
locationName: backing.locationName,
needsConversion: project.stats.needsConversion,
omitUSCurrencyCode: project.stats.omitUSCurrencyCode,
pledgeAmount: backing.amount,
pledgedOn: backing.pledgedAt,
projectCurrencyCountry: projectCurrencyCountry,
projectDeadline: project.dates.deadline,
projectState: project.state,
rewardMinimum: allRewardsTotal(for: backing),
shippingAmount: backing.shippingAmount.flatMap(Double.init),
shippingAmountHidden: backing.reward?.shipping.enabled == false,
rewardIsLocalPickup: isRewardLocalPickup
)
}
private func allRewardsTotal(for backing: Backing) -> Double {
let baseRewardAmount = backing.reward?.minimum ?? 0
guard let addOns = backing.addOns else { return baseRewardAmount }
return baseRewardAmount + addOns.reduce(0.0) { total, addOn in total.addingCurrency(addOn.minimum) }
}
private func distinctRewards(_ rewards: [Reward]) -> [Reward] {
var rewardIds: Set<Int> = []
return rewards.filter { reward in
defer { rewardIds.insert(reward.id) }
return !rewardIds.contains(reward.id)
}
}
| apache-2.0 |
iZirius/MovingHelper | MovingHelper/ViewControllers/DetailViewController.swift | 37 | 3116 | //
// DetailViewController.swift
// MovingHelper
//
// Created by Ellen Shapiro on 6/7/15.
// Copyright (c) 2015 Razeware. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
//MARK: Properties
// @IBOutlet weak var editSaveButton: UIBarButtonItem!
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var doneCheckbox: Checkbox!
@IBOutlet weak var daysRemainingLabel: UILabel!
@IBOutlet weak var dueDatePicker: UIPickerView!
@IBOutlet weak var notesTextView: UITextView!
var detailTask: Task?
var moveDate: NSDate!
var inEditMode = false {
didSet {
if (inEditMode) {
titleTextField.borderStyle = .Bezel
notesTextView.layer.borderWidth = 1
notesTextView.editable = false
titleTextField.enabled = false
} else {
titleTextField.enabled = true
notesTextView.editable = true
titleTextField.borderStyle = .None
notesTextView.layer.borderWidth = 0
}
}
}
//MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
moveDate = NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultKey.MovingDate.rawValue) as! NSDate
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
configureForCurrentTask()
}
//MARK: IBActions
@IBAction func checkboxToggled() {
detailTask!.done = !detailTask!.done
}
//MARK: Task-based UI updates
private func configureForCurrentTask() {
if let task: Task = detailTask {
title = task.title
titleTextField.text = task.title
doneCheckbox.isChecked = task.done
dueDatePicker.selectRow(task.dueDate.getIndex(),
inComponent: 0,
animated: true)
updateFromDueDate(task.dueDate)
notesTextView.text = task.notes
} else {
title = LocalizedStrings.editTitle
inEditMode = true
}
}
//MARK: Due Date-based UI updates
private func updateFromDueDate(dueDate: TaskDueDate) {
daysRemainingLabel.text = dueDate.daysFromDueDate(moveDate)
if dueDate.isOverdueForMoveDate(moveDate) {
daysRemainingLabel.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5)
} else {
daysRemainingLabel.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.5)
}
}
}
//MARK: - UIPickerView Data Source Extension
extension DetailViewController: UIPickerViewDataSource {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 6
}
}
//MARK: - UIPickerView Delegate Extension
extension DetailViewController: UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return TaskDueDate.fromIndex(row).getTitle()
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let dueDate = TaskDueDate.fromIndex(row)
updateFromDueDate(dueDate)
}
}
| mit |
apple/swift-nio | Sources/NIOCore/FileDescriptor.swift | 1 | 1278 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 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
//
//===----------------------------------------------------------------------===//
public protocol FileDescriptor {
/// Will be called with the file descriptor if still open, if not it will
/// throw an `IOError`.
///
/// The ownership of the file descriptor must not escape the `body` as it's completely managed by the
/// implementation of the `FileDescriptor` protocol.
///
/// - parameters:
/// - body: The closure to execute if the `FileDescriptor` is still open.
/// - throws: If either the `FileDescriptor` was closed before or the closure throws by itself.
func withUnsafeFileDescriptor<T>(_ body: (CInt) throws -> T) throws -> T
/// `true` if this `FileDescriptor` is open (which means it was not closed yet).
var isOpen: Bool { get }
/// Close this `FileDescriptor`.
func close() throws
}
| apache-2.0 |
SmallElephant/FEDesignPattern | 8-StrategyPattern/8-StrategyPattern/ViewController.swift | 1 | 652 | //
// ViewController.swift
// 8-StrategyPattern
//
// Created by keso on 2017/6/3.
// Copyright © 2017年 FlyElephant. 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.
}
private func setUp() {
let download:Download = Download(strategy: DiskStrategy())
download.downloadFile()
}
}
| mit |
scheib/chromium | ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_view_provider.swift | 1 | 616 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import SwiftUI
import UIKit
// A provider to provide the SwiftUI OverflowMenuView to Objective C. This is
// necessary because Objective C can't see SwiftUI types.
@available(iOS 15, *)
@objcMembers public class OverflowMenuViewProvider: NSObject {
public static func makeViewController(withModel model: OverflowMenuModel) -> UIViewController {
return OverflowMenuHostingController(rootView: OverflowMenuView().environmentObject(model))
}
}
| bsd-3-clause |
kvedula/WWDC2015 | Kamesh Vedula/TimelineView.swift | 1 | 12750 | //
// TimelineView.swift
// Kamesh Vedula
//
// Created by Kamesh Vedula on 4/25/15.
// Copyright (c) Kamesh Vedula. All rights reserved.
//
import UIKit
/**
Represents an instance in the Timeline. A Timeline is built using one or more of these TimeFrames.
*/
public struct TimeFrame{
/**
A description of the event.
*/
let text: String
/**
The date that the event occured.
*/
let date: String
/**
An optional image to show with the text and the date in the timeline.
*/
let image: UIImage?
}
/**
The shape of a bullet that appears next to each event in the Timeline.
*/
public enum BulletType{
/**
Bullet shaped as a diamond with no fill.
*/
case Diamond
}
/**
View that shows the given events in bullet form.
*/
public class TimelineView: UIView {
//MARK: Public Properties
/**
The events shown in the Timeline
*/
public var timeFrames: [TimeFrame]{
didSet{
setupContent()
}
}
/**
The color of the bullets and the lines connecting them.
*/
public var lineColor: UIColor = UIColor.lightGrayColor(){
didSet{
setupContent()
}
}
/**
Color of the larger Date title label in each event.
*/
public var titleLabelColor: UIColor = UIColor(red: 0/255, green: 131/255, blue: 122/255, alpha: 1){
didSet{
setupContent()
}
}
/**
Color of the smaller Text detail label in each event.
*/
public var detailLabelColor: UIColor = UIColor(red: 110/255, green: 110/255, blue: 110/255, alpha: 1){
didSet{
setupContent()
}
}
/**
The type of bullet shown next to each element.
*/
public var bulletType: BulletType = BulletType.Diamond{
didSet{
setupContent()
}
}
//MARK: Private Properties
private var imageViewer: JTSImageViewController?
//MARK: Public Methods
/**
Note that the timeFrames cannot be set by this method. Further setup is required once this initalization occurs.
May require more work to allow this to work with restoration.
@param coder An unarchiver object.
*/
required public init(coder aDecoder: NSCoder) {
timeFrames = []
super.init(coder: aDecoder)
}
/**
Initializes the timeline with all information needed for a complete setup.
@param bulletType The type of bullet shown next to each element.
@param timeFrames The events shown in the Timeline
*/
public init(bulletType: BulletType, timeFrames: [TimeFrame]){
self.timeFrames = timeFrames
self.bulletType = bulletType
super.init(frame: CGRect.zeroRect)
setTranslatesAutoresizingMaskIntoConstraints(false)
setupContent()
}
//MARK: Private Methods
private func setupContent(){
for v in subviews{
v.removeFromSuperview()
}
let guideView = UIView()
guideView.setTranslatesAutoresizingMaskIntoConstraints(false)
addSubview(guideView)
addConstraints([
NSLayoutConstraint(item: guideView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 24),
NSLayoutConstraint(item: guideView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: guideView, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: guideView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 0)
])
var i = 0
var viewFromAbove = guideView
for element in timeFrames{
let v = blockForTimeFrame(element, imageTag: i)
addSubview(v)
addConstraints([
NSLayoutConstraint(item: v, attribute: .Top, relatedBy: .Equal, toItem: viewFromAbove, attribute: .Bottom, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: v, attribute: .Left, relatedBy: .Equal, toItem: viewFromAbove, attribute: .Left, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: v, attribute: .Width, relatedBy: .Equal, toItem: viewFromAbove, attribute: .Width, multiplier: 1.0, constant: 0),
])
viewFromAbove = v
i++
}
let extraSpace: CGFloat = 200
let line = UIView()
line.setTranslatesAutoresizingMaskIntoConstraints(false)
line.backgroundColor = lineColor
addSubview(line)
sendSubviewToBack(line)
addConstraints([
NSLayoutConstraint(item: line, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 20.5),
NSLayoutConstraint(item: line, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 1),
NSLayoutConstraint(item: line, attribute: .Top, relatedBy: .Equal, toItem: viewFromAbove, attribute: .Bottom, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: line, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: extraSpace)
])
addConstraint(NSLayoutConstraint(item: viewFromAbove, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0))
}
private func bulletView(size: CGSize, bulletType: BulletType) -> UIView {
var path: UIBezierPath
switch bulletType {
case .Diamond:
path = UIBezierPath(diamondOfSize: size)
}
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = lineColor.CGColor
shapeLayer.path = path.CGPath
let v = UIView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.width))
v.setTranslatesAutoresizingMaskIntoConstraints(false)
v.layer.addSublayer(shapeLayer)
return v
}
private func blockForTimeFrame(element: TimeFrame, imageTag: Int) -> UIView{
let v = UIView()
v.setTranslatesAutoresizingMaskIntoConstraints(false)
//bullet
let s = CGSize(width: 14, height: 14)
var bullet: UIView = bulletView(s, bulletType: bulletType)
v.addSubview(bullet)
v.addConstraints([
NSLayoutConstraint(item: bullet, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 14),
NSLayoutConstraint(item: bullet, attribute: .Top, relatedBy: .Equal, toItem: v, attribute: .Top, multiplier: 1.0, constant: 0)
])
//image
if let image = element.image{
let backgroundViewForImage = UIView()
backgroundViewForImage.setTranslatesAutoresizingMaskIntoConstraints(false)
backgroundViewForImage.backgroundColor = UIColor.blackColor()
backgroundViewForImage.layer.cornerRadius = 10
v.addSubview(backgroundViewForImage)
v.addConstraints([
NSLayoutConstraint(item: backgroundViewForImage, attribute: .Width, relatedBy: .Equal, toItem: v, attribute: .Width, multiplier: 1.0, constant: -60),
NSLayoutConstraint(item: backgroundViewForImage, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 130),
NSLayoutConstraint(item: backgroundViewForImage, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 40),
NSLayoutConstraint(item: backgroundViewForImage, attribute: .Top, relatedBy: .Equal, toItem: v, attribute: .Top, multiplier: 1.0, constant: 0)
])
let imageView = UIImageView(image: image)
imageView.layer.cornerRadius = 10
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
imageView.contentMode = UIViewContentMode.ScaleAspectFit
v.addSubview(imageView)
imageView.tag = imageTag
v.addConstraints([
NSLayoutConstraint(item: imageView, attribute: .Left, relatedBy: .Equal, toItem: backgroundViewForImage, attribute: .Left, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: imageView, attribute: .Right, relatedBy: .Equal, toItem: backgroundViewForImage, attribute: .Right, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: imageView, attribute: .Top, relatedBy: .Equal, toItem: backgroundViewForImage, attribute: .Top, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: imageView, attribute: .Bottom, relatedBy: .Equal, toItem: backgroundViewForImage, attribute: .Bottom, multiplier: 1.0, constant: 0)
])
let button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.backgroundColor = UIColor.clearColor()
button.tag = imageTag
button.addTarget(self, action: "tapImage:", forControlEvents: UIControlEvents.TouchUpInside)
v.addSubview(button)
v.addConstraints([
NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: v, attribute: .Width, multiplier: 1.0, constant: -60),
NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 130),
NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 40),
NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: v, attribute: .Top, multiplier: 1.0, constant: 0)
])
}
let y = element.image == nil ? 0 as CGFloat : 145.0 as CGFloat
let titleLabel = UILabel()
titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
titleLabel.font = UIFont(name: "ArialMT", size: 20)
titleLabel.textColor = titleLabelColor
titleLabel.text = element.date
titleLabel.numberOfLines = 0
titleLabel.layer.masksToBounds = false
v.addSubview(titleLabel)
v.addConstraints([
NSLayoutConstraint(item: titleLabel, attribute: .Width, relatedBy: .Equal, toItem: v, attribute: .Width, multiplier: 1.0, constant: -40),
NSLayoutConstraint(item: titleLabel, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 40),
NSLayoutConstraint(item: titleLabel, attribute: .Top, relatedBy: .Equal, toItem: v, attribute: .Top, multiplier: 1.0, constant: y - 5)
])
let textLabel = UILabel()
textLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
textLabel.font = UIFont(name: "ArialMT", size: 16)
textLabel.text = element.text
textLabel.textColor = detailLabelColor
textLabel.numberOfLines = 0
textLabel.layer.masksToBounds = false
v.addSubview(textLabel)
v.addConstraints([
NSLayoutConstraint(item: textLabel, attribute: .Width, relatedBy: .Equal, toItem: v, attribute: .Width, multiplier: 1.0, constant: -47),
NSLayoutConstraint(item: textLabel, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 40),
NSLayoutConstraint(item: textLabel, attribute: .Top, relatedBy: .Equal, toItem: titleLabel, attribute: .Bottom, multiplier: 1.0, constant: 5),
NSLayoutConstraint(item: textLabel, attribute: .Bottom, relatedBy: .Equal, toItem: v, attribute: .Bottom, multiplier: 1.0, constant: -10)
])
//draw the line between the bullets
let line = UIView()
line.setTranslatesAutoresizingMaskIntoConstraints(false)
line.backgroundColor = lineColor
v.addSubview(line)
sendSubviewToBack(line)
v.addConstraints([
NSLayoutConstraint(item: line, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 1),
NSLayoutConstraint(item: line, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 20.5),
NSLayoutConstraint(item: line, attribute: .Top, relatedBy: .Equal, toItem: v, attribute: .Top, multiplier: 1.0, constant: 14),
NSLayoutConstraint(item: line, attribute: .Height, relatedBy: .Equal, toItem: v, attribute: .Height, multiplier: 1.0, constant: -14)
])
return v
}
func tapImage(button: UIButton){
var imageView: UIImageView? = nil
for v in subviews{
for w in v.subviews{
if w.tag == button.tag && w is UIImageView{
imageView = (w as? UIImageView)
}
}
}
if let i = imageView{
let imageInfo = JTSImageInfo()
imageInfo.image = i.image
imageInfo.referenceRect = convertRect(i.frame, fromView: i.superview)
imageInfo.referenceView = self
imageViewer = JTSImageViewController(imageInfo: imageInfo, mode: JTSImageViewControllerMode.Image, backgroundStyle: JTSImageViewControllerBackgroundStyle._ScaledDimmedBlurred)
imageViewer!.showFromViewController(UIApplication.sharedApplication().keyWindow?.rootViewController, transition: JTSImageViewControllerTransition._FromOriginalPosition)
}
}
}
extension UIBezierPath {
convenience init(diamondOfSize size: CGSize) {
self.init()
moveToPoint(CGPoint(x: size.width / 2, y: 0))
addLineToPoint(CGPoint(x: size.width, y: size.height / 2))
addLineToPoint(CGPoint(x: size.width / 2, y: size.height))
addLineToPoint(CGPoint(x: 0, y: size.width / 2))
closePath()
}
}
| mit |
SanjoDeundiak/Wardrobe | Sources/App/Models/Colors.swift | 1 | 726 | //
// Colors.swift
// Hello
//
// Created by Oleksandr Deundiak on 6/15/17.
//
//
import Foundation
enum ColorName: String {
case red = "red"
case green = "green"
case blue = "blue"
case yellow = "yellow"
case black = "black"
case white = "white"
}
enum Color {
case colorName(ColorName)
case hex(String)
init?(rawValue: String) {
if let colorName = ColorName(rawValue: rawValue) {
self = .colorName(colorName)
}
else {
self = .hex(rawValue)
}
}
var rawValue: String {
switch self {
case .colorName(let color): return color.rawValue
case .hex(let value): return value
}
}
}
| mit |
fe9lix/Protium | iOS/Protium/src/gifdetails/GifDetailsUI.swift | 1 | 2606 | import UIKit
import RxSwift
import RxCocoa
final class GifDetailsUI: InteractableUI<GifDetailsInteractor> {
@IBOutlet weak var copyEmbedLinkButton: UIButton!
@IBOutlet weak var openGiphyButton: UIButton!
let disposeBag = DisposeBag()
private var playerViewController: GifPlayerViewController?
// MARK: - Lifecycle
class func create(interactorFactory: @escaping (GifDetailsUI) -> GifDetailsInteractor) -> GifDetailsUI {
return create(
storyboard: UIStoryboard(name: "GifDetails", bundle: Bundle(for: GifDetailsUI.self)),
interactorFactory: downcast(interactorFactory)
) as! GifDetailsUI
}
deinit {
log(self)
}
// The Gif Player is shown using a container view in the storyboard and an embed segue.
// Use the "prepare" call to store a reference to GifPlayerViewController that
// starts playback when the Gif-Observable triggers.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let identifier = segue.identifier else { return }
if case .gifPlayer? = Segue(rawValue: identifier) {
playerViewController = segue.destination as? GifPlayerViewController
}
}
override func viewDidLoad() {
copyEmbedLinkButton.setTitle("GifDetails.CopyEmbedLink".localized, for: .normal)
openGiphyButton.setTitle("GifDetails.OpenGiphy".localized, for: .normal)
super.viewDidLoad()
}
// MARK: - Bindings
override func bindInteractor(interactor: GifDetailsInteractor) {
interactor.gif.drive(onNext: { gif in
self.playVideo(url: gif.videoURL)
}).addDisposableTo(disposeBag)
interactor.gif
.map { $0.embedURL == nil }
.drive(self.copyEmbedLinkButton.rx.isHidden)
.addDisposableTo(disposeBag)
}
// MARK: - Video Playback
private func playVideo(url: URL?) {
guard let url = url, let playerViewController = playerViewController else { return }
playerViewController.play(url: url)
}
}
extension GifDetailsUI {
struct Actions {
let copyEmbedLink: Driver<Void>
let openGiphy: Driver<Void>
}
var actions: Actions {
return Actions(
copyEmbedLink: copyEmbedLinkButton.rx.tap.asDriver(),
openGiphy: openGiphyButton.rx.tap.asDriver()
)
}
}
extension GifDetailsUI {
enum Segue: String {
case gifPlayer
}
}
| mit |
ali-rantakari/Punos | PunosTests/ResponseMockingTests.swift | 1 | 15738 | //
// ResponseMockingTests.swift
// Punos
//
// Created by Ali Rantakari on 12.2.16.
// Copyright © 2016 Ali Rantakari. All rights reserved.
//
import XCTest
import Punos
class ResponseMockingTests: MockServerTestCase {
func testResponseMocking_defaultsWhenNoMockResponsesConfigured() {
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 200)
XCTAssertEqual(response.allHeaderNames, ["Connection"])
XCTAssertEqual(data.count, 0)
XCTAssertNil(error)
}
}
func testResponseMocking_defaultMockResponseWithNoMatcher() {
let mockData = "foofoo".data(using: String.Encoding.utf16)!
server.mockResponse(
status: 201,
data: mockData,
headers: ["X-Greeting": "Hey yall", "Content-Type": "thing/foobar"],
onlyOnce: false,
matcher: nil)
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
XCTAssertEqual(response.allHeaderNames, ["X-Greeting", "Content-Type", "Content-Length", "Connection"])
XCTAssertEqual(response.headerWithName("X-Greeting"), "Hey yall")
XCTAssertEqual(response.headerWithName("Content-Type"), "thing/foobar")
XCTAssertEqual(response.headerWithName("Content-Length"), "\(mockData.count)")
XCTAssertEqual(data, mockData)
XCTAssertNil(error)
}
}
func testResponseMocking_defaultMockResponseWithNoMatcher_overriding() {
server.mockResponse(status: 201)
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
server.mockResponse(status: 202)
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
}
func testResponseMocking_defaultMockResponseWithNoMatcher_overriding_withOnlyOnceBefore() {
server.mockResponse(status: 202, onlyOnce: true)
server.mockResponse(status: 201)
server.mockResponse(status: 203) // Overrides previously configured 201
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 202) // 202 onlyOnce
}
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 203) // fallback
}
}
func testResponseMocking_matcher() {
server.mockResponse(status: 500) // default fallback
server.mockResponse(status: 202) { request in
return (request.method == "GET" && request.path.contains("foo"))
}
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
request("GET", "/dom/xfoobar/gg") { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
request("POST", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 500)
}
request("GET", "/oof") { data, response, error in
XCTAssertEqual(response.statusCode, 500)
}
}
func testResponseMocking_matcher_matchByData() {
let dataToMatchOn = "woohoo".data(using: String.Encoding.utf8)
let otherData = "something else".data(using: String.Encoding.utf8)
server.mockResponse(status: 500) // default fallback
server.mockResponse(status: 202) { request in
return request.data == dataToMatchOn
}
request("POST", "/foo", data: dataToMatchOn) { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
request("POST", "/dom/xfoobar/gg", data: dataToMatchOn) { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
request("POST", "/foo") { data, response, error in // no data
XCTAssertEqual(response.statusCode, 500)
}
request("POST", "/foo2", data: otherData) { data, response, error in
XCTAssertEqual(response.statusCode, 500)
}
}
func testResponseMocking_matcher_overlapping() {
server.mockResponse(status: 201) { request in
return request.path.contains("foo")
}
server.mockResponse(status: 202) { request in
return request.path.contains("bar")
}
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
request("GET", "/bar") { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
// Both match --> 1st one added wins
request("GET", "/foobar") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
}
func testResponseMocking_matcher_viaEndpointParameter() {
server.mockResponse(endpoint: "GET /foo", status: 201)
server.mockResponse(endpoint: "GET /bar", status: 202)
server.mockResponse(endpoint: "GET /bar/baz", status: 203)
server.mockResponse(endpoint: "GET /", status: 204)
server.mockResponse(status: 500) // default fallback
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
request("GET", "/bar") { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
request("GET", "/bar?a=1") { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
request("GET", "/bar?a=1&b=2") { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
request("GET", "/bar/baz") { data, response, error in
XCTAssertEqual(response.statusCode, 203)
}
request("GET", "/") { data, response, error in
XCTAssertEqual(response.statusCode, 204)
}
request("POST", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 500, "Method doesn't match")
}
// If `matcher` and `endpoint` are both given, `endpoint`
// takes precedence:
//
server.mockResponse(endpoint: "GET /both", status: 201) { req in return false }
request("GET", "/both") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
}
func testResponseMocking_matcher_viaEndpointParameter_methodOnly() {
server.mockResponse(endpoint: "GET", status: 201)
server.mockResponse(status: 500) // default fallback
request("GET", "") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
request("GET", "/") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
request("GET", "/bar") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
request("POST", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 500, "Method doesn't match")
}
}
func testResponseMocking_onlyOnce_withoutMatcher() {
// The responses should be dealt in the same order in which they were configured:
//
server.mockResponse(status: 201, onlyOnce: true)
server.mockResponse(status: 202, onlyOnce: true)
server.mockResponse(status: 203, onlyOnce: true)
server.mockResponse(status: 500) // default fallback
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 203)
}
// All three 'onlyOnce' responses are exhausted — we should get the fallback:
request("POST", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 500)
}
}
func testResponseMocking_onlyOnce_withMatcher() {
server.mockResponse(status: 500) // default fallback
let matcher: MockResponseMatcher = { request in request.path == "/match-me" }
server.mockResponse(status: 201, onlyOnce: true, matcher: matcher)
server.mockResponse(status: 202, onlyOnce: true, matcher: matcher)
server.mockResponse(status: 203, onlyOnce: true, matcher: matcher)
request("GET", "/match-me") { data, response, error in
XCTAssertEqual(response.statusCode, 201)
}
// Try one non-matching request "in between":
request("POST", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 500)
}
request("GET", "/match-me") { data, response, error in
XCTAssertEqual(response.statusCode, 202)
}
request("GET", "/match-me") { data, response, error in
XCTAssertEqual(response.statusCode, 203)
}
// All three 'onlyOnce' responses are exhausted — we should get the fallback:
request("POST", "/match-me") { data, response, error in
XCTAssertEqual(response.statusCode, 500)
}
}
func testResponseMocking_delay() {
// Let's try to keep the delay short enough to not make our
// tests slow, but long enough for us to reliably check that
// it was intentional and not accidental
//
let delayToTest: TimeInterval = 0.5
// First try with NO delay:
//
server.mockResponse(status: 205, delay: 0)
let noDelayStartDate = Date()
request("GET", "/foo") { data, response, error in
let endDate = Date()
XCTAssertEqual(response.statusCode, 205)
XCTAssertLessThan(endDate.timeIntervalSince(noDelayStartDate), 0.1)
}
// Then try with the delay:
//
server.clearMockResponses()
server.mockResponse(status: 201, delay: delayToTest)
let withDelayStartDate = Date()
request("GET", "/foo") { data, response, error in
let endDate = Date()
XCTAssertEqual(response.statusCode, 201)
XCTAssertGreaterThan(endDate.timeIntervalSince(withDelayStartDate), delayToTest)
}
}
func testResponseMocking_jsonString() {
server.mockJSONResponse(status: 501, json: "{\"greeting\": \"Moro\"}")
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 501)
XCTAssertEqual(response.headerWithName("Content-Type"), "application/json")
XCTAssertEqual(String(data: data, encoding: String.Encoding.utf8), "{\"greeting\": \"Moro\"}")
}
}
func testResponseMocking_jsonObject() {
server.mockJSONResponse(status: 501, object: ["greeting": "Moro"])
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 501)
XCTAssertEqual(response.headerWithName("Content-Type"), "application/json")
XCTAssertEqual(String(data: data, encoding: String.Encoding.utf8), "{\"greeting\":\"Moro\"}")
}
}
func testMockResponseJSONSupport() throws {
XCTAssertEqual(try MockResponse(statusCode: 507, jsonObject: [3]).statusCode, 507)
// Handling of headers
XCTAssertEqual(try MockResponse(statusCode: 507, jsonObject: [3]).headers?["Content-Type"], "application/json")
XCTAssertEqual(try MockResponse(statusCode: 507, jsonObject: [3], headers: ["Foo": "Bar"]).headers?["Content-Type"], "application/json")
XCTAssertEqual(try MockResponse(statusCode: 507, jsonObject: [3], headers: ["Foo": "Bar"]).headers?["Foo"], "Bar")
// Serialization and deserialization
XCTAssertEqual((try JSONSerialization.jsonObject(with: try MockResponse(statusCode: 507, jsonObject: ["baz": 7]).data ?? Data(), options: []) as? [String:Int])?["baz"], 7)
XCTAssertEqual((try MockResponse(statusCode: 507, jsonObject: ["baz": 7]).jsonData as? [String:Int])?["baz"], 7)
}
func testResponseMocking_AdHoc() {
var requestReceivedByHandler: HTTPRequest?
server.mockAdHocResponse { request in
requestReceivedByHandler = request
return MockResponse(
statusCode: 507,
data: "adhoc".data(using: .utf8),
headers: [
"X-Adhoc": "adhoc!"
])
}
request("GET", "/foo/bar%20baz?a=b") { data, response, error in
XCTAssertNotNil(requestReceivedByHandler)
XCTAssertEqual(requestReceivedByHandler!.method, "GET")
XCTAssertEqual(requestReceivedByHandler!.path, "/foo/bar%20baz")
XCTAssertEqual(requestReceivedByHandler!.query["a"], "b")
XCTAssertEqual(response.statusCode, 507)
XCTAssertEqual(String(data: data, encoding: .utf8), "adhoc")
XCTAssertEqual(response.headerWithName("X-Adhoc"), "adhoc!")
}
server.clearAllMockingState()
request("GET", "/foo/bar%20baz?a=b") { data, response, error in
XCTAssertEqual(response.statusCode, 200)
}
}
func testResponseMocking_AdHoc_TakesPrecedenceOverStaticMockResponses() {
server.mockResponse(endpoint: nil, status: 300)
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 300)
}
server.mockAdHocResponse { request in
return MockResponse(
statusCode: 507,
data: nil,
headers: nil)
}
request("GET", "/foo") { data, response, error in
XCTAssertEqual(response.statusCode, 507)
}
}
func testResponseMocking_AdHoc_InvokedInOrder_SomeReturnNil() {
server.mockResponse(endpoint: nil, status: 300)
server.mockAdHocResponse { request in
guard request.path.contains("first") else { return nil }
return MockResponse(statusCode: 501, data: nil, headers: nil)
}
server.mockAdHocResponse { request in
guard request.path.contains("second") else { return nil }
return MockResponse(statusCode: 502, data: nil, headers: nil)
}
server.mockAdHocResponse { request in
guard request.path.contains("third") else { return nil }
return MockResponse(statusCode: 503, data: nil, headers: nil)
}
request("GET", "/first") { data, response, error in
XCTAssertEqual(response.statusCode, 501, "Matches 1st ad-hoc handler")
}
request("GET", "/second") { data, response, error in
XCTAssertEqual(response.statusCode, 502, "Matches 2nd ad-hoc handler")
}
request("GET", "/third") { data, response, error in
XCTAssertEqual(response.statusCode, 503, "Matches 3rd ad-hoc handler")
}
request("GET", "/fourth") { data, response, error in
XCTAssertEqual(response.statusCode, 300, "Matches none of the ad-hoc handlers")
}
}
}
| mit |
davidchiles/OSMKit-Swift | Tests/ModelTest.swift | 2 | 3149 | //
// ModelTest.swift
// OSMKit-Swift
//
// Created by David Chiles on 12/15/15.
// Copyright © 2015 David Chiles. All rights reserved.
//
import XCTest
@testable import OSMKit_Swift
let tags = ["key1":"value1","key2":"value2"]
let elementAttributes = ["version":"2","id":"35719005","visible":"true","timestamp":"2009-10-21T02:05:20Z","user":"Speight","uid":"24452","changeset":"2908326"]
public func testNode() -> OSMNode {
var nodeAttributes = elementAttributes
nodeAttributes["lat"] = "37.8815080"
nodeAttributes["lon"] = "-122.2319067"
let node = OSMNode(xmlAttributes: nodeAttributes)
node.tags = tags
return node
}
public func testWay() -> OSMWay {
let way = OSMWay(xmlAttributes: elementAttributes)
way.nodes = [1,2,3,4,5,6,7]
return way
}
public func testRelation() -> OSMRelation {
let relation = OSMRelation(xmlAttributes: elementAttributes)
let member1 = OSMRelationMember(member: OSMID(type: .Node, ref: 1), role: nil)
let member2 = OSMRelationMember(member: OSMID(type: .Way, ref: 34), role: "forward")
let member3 = OSMRelationMember(member: OSMID(type: .Relation, ref: 22334), role: "backward")
relation.members = [member1,member2,member3]
return relation
}
class ModelTest: XCTestCase {
let version = 2
let id:Int64 = 35719005
let lon = -122.2319067
let lat = 37.8815080
let visible = true
let changeset:Int64 = 2908326
var date = NSDate()
override func setUp() {
super.setUp()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let dateComponents = NSDateComponents()
dateComponents.day = 21
dateComponents.month = 10
dateComponents.year = 2009
dateComponents.hour = 2
dateComponents.minute = 5
dateComponents.second = 20
dateComponents.timeZone = NSTimeZone(forSecondsFromGMT: 0)
self.date = (calendar?.dateFromComponents(dateComponents))!
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testNodeModel() {
let node = testNode()
XCTAssertEqual(self.version, node.version)
XCTAssertEqual(self.id, node.osmIdentifier)
XCTAssertEqual(self.lat, node.latitude)
XCTAssertEqual(self.lon, node.longitude)
XCTAssertEqual(self.changeset, node.changeset)
XCTAssertEqual(self.visible, node.visible)
XCTAssertEqual(self.date, node.timeStamp)
let coordinate = node.coordinate
XCTAssertEqual(self.lat, coordinate.latitude)
XCTAssertEqual(self.lon, coordinate.longitude)
node.addTag("key", value: "value")
let tagsEqual = node.tags! == ["key":"value","key1":"value1","key2":"value2"]
XCTAssertTrue(tagsEqual)
}
func testNodePerformance() {
// This is an example of a performance test case.
self.measureBlock {
for _ in 1...1000 {
_ = testNode()
}
}
}
}
| mit |
SteveRohrlack/CitySimCore | Tests/RessourceTypeTests.swift | 1 | 2101 | //
// RessourceTypeTests.swift
// CitySimCore
//
// Created by Steve Rohrlack on 08.06.16.
// Copyright © 2016 Steve Rohrlack. All rights reserved.
//
import XCTest
#if os(iOS)
@testable import CitySimCoreiOS
#endif
#if os(OSX)
@testable import CitySimCoreMacOS
#endif
class RessourceTypeTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testValue() {
let ressourceType: RessourceType = .Electricity(10)
XCTAssertEqual(10, ressourceType.value())
}
func testOperatorGreaterEqual() {
let ressourceType1: RessourceType = .Electricity(10)
let ressourceType2: RessourceType = .Electricity(20)
let ressourceTypeNil: RessourceType = .Electricity(nil)
XCTAssertEqual(true, ressourceType1 <= ressourceType2)
XCTAssertEqual(false, ressourceType1 <= ressourceTypeNil)
}
func testOperatorLesserEqual() {
let ressourceType1: RessourceType = .Electricity(10)
let ressourceType2: RessourceType = .Electricity(20)
let ressourceTypeNil: RessourceType = .Electricity(nil)
XCTAssertEqual(true, ressourceType1 <= ressourceType2)
XCTAssertEqual(false, ressourceType1 <= ressourceTypeNil)
}
func testOperatorEqual() {
let ressourceType1: RessourceType = .Electricity(10)
let ressourceType2: RessourceType = .Electricity(10)
let ressourceTypeNil: RessourceType = .Electricity(nil)
XCTAssertEqual(true, ressourceType1 == ressourceType2)
XCTAssertEqual(false, ressourceType1 == ressourceTypeNil)
XCTAssertEqual(false, ressourceType1 != ressourceType2)
}
func testConsumerConsumes() {
let ressourceConsumer = RessourceConsumerTestDouble(ressources: [.Electricity(1)])
XCTAssertEqual(true, ressourceConsumer.consumes(ressource: .Electricity(nil)))
XCTAssertEqual(false, ressourceConsumer.consumes(ressource: .Water(nil)))
}
} | mit |
skedgo/tripkit-ios | Sources/TripKitUI/cards/TKUIRoutingResultsMapManager.swift | 1 | 7263 | //
// TKUIRoutingResultsMapManager.swift
// TripKit
//
// Created by Adrian Schoenig on 13/4/17.
// Copyright © 2017 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import MapKit
import RxSwift
import RxCocoa
import TGCardViewController
import TripKit
/// An item to be displayed on the map
public struct TKUIRoutingResultsMapRouteItem {
let trip: Trip
public let polyline: TKRoutePolyline
public let selectionIdentifier: String
init?(_ trip: Trip) {
self.trip = trip
self.selectionIdentifier = trip.objectID.uriRepresentation().absoluteString
let displayableShapes = trip.segments
.compactMap { $0.shapes.isEmpty ? nil : $0.shapes } // Only include those with shapes
.flatMap { $0.filter { $0.routeIsTravelled } } // Flat list of travelled shapes
let route = displayableShapes
.reduce(into: TKColoredRoute(path: [], identifier: selectionIdentifier)) { $0.append($1.sortedCoordinates ?? []) }
guard let polyline = TKRoutePolyline(route: route) else { return nil }
self.polyline = polyline
}
}
public protocol TKUIRoutingResultsMapManagerType: TGCompatibleMapManager {
@MainActor
var droppedPin: Signal<CLLocationCoordinate2D> { get }
@MainActor
var selectedMapRoute: Signal<TKUIRoutingResultsMapRouteItem> { get }
}
class TKUIRoutingResultsMapManager: TKUIMapManager, TKUIRoutingResultsMapManagerType {
weak var viewModel: TKUIRoutingResultsViewModel?
private let zoomToDestination: Bool
init(destination: MKAnnotation? = nil, zoomToDestination: Bool) {
self.zoomToDestination = zoomToDestination
super.init()
self.destinationAnnotation = destination
self.preferredZoomLevel = .road
self.showOverlayPolygon = true
}
private var dropPinRecognizer = UILongPressGestureRecognizer()
private var droppedPinPublisher = PublishSubject<CLLocationCoordinate2D>()
var droppedPin: Signal<CLLocationCoordinate2D> {
return droppedPinPublisher.asSignal(onErrorSignalWith: .empty())
}
private var tapRecognizer = UITapGestureRecognizer()
private var selectedRoutePublisher = PublishSubject<TKUIRoutingResultsMapRouteItem>()
var selectedMapRoute: Signal<TKUIRoutingResultsMapRouteItem> {
return selectedRoutePublisher.asSignal(onErrorSignalWith: .empty())
}
private var disposeBag = DisposeBag()
private var originAnnotation: MKAnnotation? {
didSet {
if let old = oldValue {
mapView?.removeAnnotation(old)
}
if let new = originAnnotation {
mapView?.addAnnotation(new)
}
}
}
private var destinationAnnotation: MKAnnotation? {
didSet {
guard let mapView = mapView else { return }
if let old = oldValue {
mapView.removeAnnotation(old)
}
if let new = destinationAnnotation {
mapView.addAnnotation(new)
}
}
}
fileprivate var selectedRoute: TKUIRoutingResultsMapRouteItem? {
didSet {
selectionIdentifier = selectedRoute?.selectionIdentifier
}
}
private var allRoutes: [TKUIRoutingResultsMapRouteItem] = [] {
didSet {
guard let mapView = mapView else { return }
let oldPolylines = oldValue.map { $0.polyline }
mapView.removeOverlays(oldPolylines)
let newPolylines = allRoutes.map { $0.polyline }
mapView.addOverlays(newPolylines)
if oldPolylines.isEmpty && !newPolylines.isEmpty {
// Zoom to the new polylines plus 20% padding around them
let boundingRect = newPolylines.boundingMapRect
let zoomToRect = boundingRect.insetBy(dx: boundingRect.size.width * -0.2, dy: boundingRect.size.height * -0.2)
zoom(to: zoomToRect, animated: true)
}
}
}
override func takeCharge(of mapView: MKMapView, animated: Bool) {
super.takeCharge(of: mapView, animated: animated)
guard let viewModel = viewModel else { assertionFailure(); return }
let zoomTo = [originAnnotation, destinationAnnotation].compactMap { $0 }
if zoomToDestination, !zoomTo.isEmpty {
self.zoom(to: zoomTo, animated: true)
}
viewModel.originAnnotation
.drive(onNext: { [weak self] in self?.originAnnotation = $0 })
.disposed(by: disposeBag)
viewModel.destinationAnnotation
.drive(onNext: { [weak self] in self?.destinationAnnotation = $0 })
.disposed(by: disposeBag)
viewModel.mapRoutes
.drive(onNext: { [weak self] in
self?.selectedRoute = $1
self?.allRoutes = $0
})
.disposed(by: disposeBag)
// Interaction
mapView.addGestureRecognizer(dropPinRecognizer)
dropPinRecognizer.rx.event
.filter { $0.state == .began }
.map { [unowned mapView] in
let point = $0.location(in: mapView)
return mapView.convert(point, toCoordinateFrom: mapView)
}
.bind(to: droppedPinPublisher)
.disposed(by: disposeBag)
mapView.addGestureRecognizer(tapRecognizer)
tapRecognizer.rx.event
.filter { $0.state == .ended }
.filter { [unowned self] _ in !self.allRoutes.isEmpty }
.map { [unowned mapView] in
let point = $0.location(in: mapView)
return mapView.convert(point, toCoordinateFrom: mapView)
}
.map { [unowned self] in self.closestRoute(to: $0) }
.filter { $0 != nil }
.map { $0! }
.bind(to: selectedRoutePublisher)
.disposed(by: disposeBag)
}
override func cleanUp(_ mapView: MKMapView, animated: Bool) {
disposeBag = DisposeBag()
// clean up map annotations and overlays
originAnnotation = nil
destinationAnnotation = nil
selectedRoute = nil
allRoutes = []
mapView.removeGestureRecognizer(dropPinRecognizer)
mapView.removeGestureRecognizer(tapRecognizer)
super.cleanUp(mapView, animated: animated)
}
private func closestRoute(to coordinate: CLLocationCoordinate2D) -> TKUIRoutingResultsMapRouteItem? {
let mapPoint = MKMapPoint(coordinate)
return allRoutes
.filter { $0 != selectedRoute }
.min { $0.distance(to: mapPoint) < $1.distance(to: mapPoint) }
}
}
extension TKUIRoutingResultsMapRouteItem {
fileprivate func distance(to mapPoint: MKMapPoint) -> CLLocationDistance {
return polyline.closestPoint(to: mapPoint).distance
}
}
// MARK: - MKMapViewDelegate
extension TKUIRoutingResultsMapManager {
override func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation === mapView.userLocation {
return nil // Use the default MKUserLocation annotation
}
// for whatever reason reuse breaks callouts when remove and re-adding views to change their colours, so we just always create a new one.
let view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: nil)
if annotation === originAnnotation {
view.pinTintColor = .green
} else if annotation === destinationAnnotation {
view.pinTintColor = .red
} else {
view.pinTintColor = .purple
}
view.animatesDrop = true
view.isDraggable = true
view.annotation = annotation
view.alpha = 1
view.canShowCallout = true
return view
}
}
| apache-2.0 |
shirokova/CustomAlert | CustomAlert/Classes/CustomAlert.swift | 1 | 1410 | //
// UIViewController+CustomAlert.swift
// Pods
//
// Created by Anna Shirokova on 11/09/2017.
//
//
import UIKit
public protocol CustomAlertDelegate: class {
func dismissAlert(animated: Bool)
func dismissAlert(animated: Bool, completion: @escaping () -> Void)
}
open class CustomAlertView: UIView {
public weak var delegate: CustomAlertDelegate?
}
public class CustomAlert {
let config: CustomAlertConfig
let builder: () -> UIView
static var globalPresentationWindow: UIWindow?
private var alertController: CustomAlertController!
var alertView: UIView!
public var isPresented: Bool {
return alertController?.presentingViewController != nil
}
func createAlertController() -> CustomAlertController {
alertController = CustomAlertController()
alertController!.config = config
alertView = builder()
alertController!.addAlertView(alertView)
(alertView as? CustomAlertView)?.delegate = alertController
return alertController!
}
public init(config: CustomAlertConfig = .default, builder: @escaping () -> UIView) {
self.config = config
self.builder = builder
}
public func dismiss(animated: Bool = true) {
alertController.dismissAlert(animated: animated) { [weak self] in
self?.alertController = nil
self?.alertView = nil
}
}
}
| mit |
yariksmirnov/ExSwift | ExSwiftTests/ExSwiftNSDateTests.swift | 3 | 9763 | //
// ExSfitNSDateTests.swift
// ExSwift
//
// Created by Piergiuseppe Longo on 23/11/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import XCTest
class ExSwiftNSDataTests: XCTestCase {
let dateFormatter = NSDateFormatter()
var startDate: NSDate?
override func setUp() {
super.setUp()
dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ss"
startDate = dateFormatter.dateFromString("30/11/1988 00:00:00")
}
// MARK: NSDate Manipulation
func testAddSeconds() {
var expectedDate = dateFormatter.dateFromString("30/11/1988 00:00:42")
var result = startDate?.addSeconds(42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(seconds:42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
expectedDate = dateFormatter.dateFromString("29/11/1988 23:59:18")
result = startDate?.addSeconds(-42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(seconds:-42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
}
func testAddMinutes() {
var expectedDate = dateFormatter.dateFromString("30/11/1988 00:42:00")
var result = startDate?.addMinutes(42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(minutes:42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
expectedDate = dateFormatter.dateFromString("29/11/1988 23:18:00")
result = startDate?.addMinutes(-42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(minutes:-42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
}
func testAddHours() {
var expectedDate = dateFormatter.dateFromString("01/12/1988 18:00:00")
var result = startDate?.addHours(42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(hours:42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
expectedDate = dateFormatter.dateFromString("28/11/1988 06:00:00")
result = startDate?.addHours(-42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(hours:-42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
}
func testAddDays() {
var expectedDate = dateFormatter.dateFromString("02/12/1988 00:00:00")
var result = startDate?.addDays(2)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(days:2)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
expectedDate = dateFormatter.dateFromString("19/10/1988 00:00:00")
result = startDate?.addDays(-42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(days:-42)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
}
func testAddWeeks() {
var expectedDate = dateFormatter.dateFromString("7/12/1988 00:00:00")
var result = startDate?.addWeeks(1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(weeks:1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
expectedDate = dateFormatter.dateFromString("23/11/1988 00:00:00")
result = startDate?.addWeeks(-1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(weeks:-1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
}
func testAddMonths() {
var expectedDate = dateFormatter.dateFromString("30/12/1988 00:00:00")
var result = startDate?.addMonths(1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(months:1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
expectedDate = dateFormatter.dateFromString("30/10/1988 00:00:00")
result = startDate?.addMonths(-1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(months:-1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
}
func testAddYears() {
var expectedDate = dateFormatter.dateFromString("30/11/1989 00:00:00")
var result = startDate?.addYears(1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(years:1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
expectedDate = dateFormatter.dateFromString("30/11/1987 00:00:00")
result = startDate?.addYears(-1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
result = startDate?.add(years:-1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
}
func testAdd(){
var expectedDate = dateFormatter.dateFromString("10/01/1990 18:42:42")
var result = startDate?.addMonths(1)
result = startDate?.add(seconds: 42, minutes: 42, hours: 42, days: 2, weeks: 1 , months: 1, years: 1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
expectedDate = dateFormatter.dateFromString("20/10/1987 22:17:18")
result = startDate?.add(seconds: -42, minutes: -42, hours: -1, days: -2, weeks: -1 , months: -1, years: -1)
XCTAssertEqual(expectedDate!, result!, "Date mismatch")
}
// MARK: Date comparison
func testIsAfter(){
var date = NSDate()
var futureDate = date.addSeconds(42)
var pastDate = date.addSeconds(-42)
XCTAssertTrue(futureDate.isAfter(date), "Future date should be in the future")
XCTAssertFalse(date.isAfter(date), "Past date should be in the past")
XCTAssertFalse(pastDate.isAfter(date), "Past date should be in the past")
}
func testIsBefore(){
var date = NSDate()
var futureDate = date.addSeconds(42)
var pastDate = date.addSeconds(-42)
XCTAssertFalse(futureDate.isBefore(date), "Future date should be in the future")
XCTAssertTrue(pastDate.isBefore(date), "Past date should be in the past")
XCTAssertFalse(date.isAfter(date), "Past date should be in the past")
}
// MARK: Getter
func testGetter() {
XCTAssertEqual(1988, startDate!.year, "Year Mismatch")
XCTAssertEqual(11, startDate!.month, "Month Mismatch")
XCTAssertEqual(30, startDate!.days, "Day Mismatch")
XCTAssertEqual(0, startDate!.hours, "Hours Mismatch")
XCTAssertEqual(0, startDate!.minutes, "Minutes Mismatch")
XCTAssertEqual(0, startDate!.seconds, "Seconds Mismatch")
XCTAssertEqual(4, startDate!.weekday, "Weekmonth Mismatch")
XCTAssertEqual(5, startDate!.weekMonth, "Weekmonth Mismatch")
}
// MARK: Comparable
func testSorting () {
var firstDate = startDate!.addSeconds(0)
var secondDate = startDate!.addSeconds(42)
var thirdDate = startDate!.addSeconds(-42)
var fourthDate = startDate!.addSeconds(-84)
var fifthDate = startDate!.addSeconds(84)
var dates : [NSDate] = [thirdDate, secondDate, firstDate, fourthDate, fifthDate]
let expected : [NSDate] = [fifthDate, secondDate, firstDate, thirdDate, fourthDate]
let expectedReverded = expected.reverse()
for i in 0 ... 42 {
dates.shuffle()
dates.sort( { $0 > $1 } )
XCTAssertEqual(expected, dates, "Sort mismatch")
dates.sort( { $0 < $1 } )
XCTAssertEqual(expectedReverded, dates, "Sort mismatch")
}
}
func testComparable(){
var date = startDate!.addSeconds(-42)
var anotherDate = startDate!.addSeconds(42)
let shouldBeTheSameDate = NSDate(timeInterval: 0, sinceDate: startDate!)
XCTAssertTrue(startDate > date, "Date should be greater")
XCTAssertFalse(startDate > anotherDate, "Date shouldn't be greater")
XCTAssertFalse(startDate > shouldBeTheSameDate, "Date shouldn't be greater")
XCTAssertTrue(startDate < anotherDate, "Date should be lower")
XCTAssertFalse(startDate < date, "Date shouldn't be lower")
XCTAssertFalse(startDate < shouldBeTheSameDate, "Date shouldn't be lower")
XCTAssertTrue(startDate >= shouldBeTheSameDate, "Date should be greater or equal")
XCTAssertTrue(startDate >= date, "Date should be greater or equal")
XCTAssertFalse(startDate >= anotherDate, "Date shouldn't be greater or equal")
XCTAssertTrue(startDate <= shouldBeTheSameDate, "Date should be lower or equal")
XCTAssertTrue(startDate < anotherDate, "Date should be lower")
XCTAssertFalse(startDate <= date, "Date shouldn't be greater or equal")
XCTAssertFalse(date == startDate, "Date should mismatch")
XCTAssertFalse(anotherDate == startDate, "Date should mismatch")
XCTAssertTrue(shouldBeTheSameDate == startDate, "Date shouldn't mismatch")
}
func testArithmetic() {
let date = NSDate() as NSDate
XCTAssertTrue(date.timeIntervalSinceDate(date - 1.hour) == 1.hour)
XCTAssertTrue(date.timeIntervalSinceDate(date + 1.hour) == -1.hour)
var otherDate = date
otherDate -= 1.minute
XCTAssertFalse(otherDate === date)
XCTAssertTrue(date.timeIntervalSinceDate(otherDate) == 1.minute)
otherDate += 1.hour
XCTAssertTrue(date.timeIntervalSinceDate(otherDate) == 1.minute - 1.hour)
}
}
| bsd-2-clause |
arvedviehweger/swift | test/IRGen/generic_class_anyobject.swift | 4 | 498 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=i386_or_x86_64
// REQUIRES: objc_interop
func foo<T: AnyObject>(_ x: T) -> T { return x }
// CHECK-LABEL: define hidden swiftcc %objc_object* @_T023generic_class_anyobject3bars9AnyObject_psAC_pF(%objc_object*)
// CHECK: call swiftcc %objc_object* @_T023generic_class_anyobject3foo{{[_0-9a-zA-Z]*}}F
func bar(_ x: AnyObject) -> AnyObject { return foo(x) }
| apache-2.0 |
duming91/Hear-You | Hear You/Extensions/CGRect+Extension.swift | 1 | 2217 | //
// CGRect+Hello.swift
// Hello
//
// Created by snow on 16/3/23.
// Copyright © 2016年 snow. All rights reserved.
//
import UIKit
extension CGRect {
var x: CGFloat {
get {
return self.origin.x
}
set {
self = CGRectMake(newValue, self.y, self.width, self.height)
}
}
var y: CGFloat {
get {
return self.origin.y
}
set {
self = CGRectMake(self.x, newValue, self.width, self.height)
}
}
var width: CGFloat {
get {
return self.size.width
}
set {
self = CGRectMake(self.x, self.y, newValue, self.height)
}
}
var height: CGFloat {
get {
return self.size.height
}
set {
self = CGRectMake(self.x, self.y, self.width, newValue)
}
}
var top: CGFloat {
get {
return self.origin.y
}
set {
y = newValue
}
}
var bottom: CGFloat {
get {
return self.origin.y + self.size.height
}
set {
self = CGRectMake(x, newValue - height, width, height)
}
}
var left: CGFloat {
get {
return self.origin.x
}
set {
self.x = newValue
}
}
var right: CGFloat {
get {
return x + width
}
set {
self = CGRectMake(newValue - width, y, width, height)
}
}
var midX: CGFloat {
get {
return self.x + self.width / 2
}
set {
self = CGRectMake(newValue - width / 2, y, width, height)
}
}
var midY: CGFloat {
get {
return self.y + self.height / 2
}
set {
self = CGRectMake(x, newValue - height / 2, width, height)
}
}
var center: CGPoint {
get {
return CGPointMake(self.midX, self.midY)
}
set {
self = CGRectMake(newValue.x - width / 2, newValue.y - height / 2, width, height)
}
}
}
| gpl-3.0 |
Rep2/SimplerNews | Sources/App/Google.swift | 1 | 2971 | import Vapor
import HTTP
import Foundation
import Dispatch
final class Google {
let serverKey = "AIzaSyCBRqxdYBflBz764vRu6kjlBTx66VlROMM"
func login(request: Request) throws -> ResponseRepresentable {
guard let idToken = request.data["id_token"]?.string else {
throw Abort.custom(status: .badRequest, message: "Parameter id_token:string is required")
}
let (userId, email) = try verifyUser(idToken: idToken)
let accessToken = UUID().uuidString
DispatchQueue.global(qos: .utility).async {
do {
var user = self.fetchUser(email: email, accessToken: accessToken)
let userProfile = try self.fetchUserProfile(userId: userId, user: user)
user.googleJSON = userProfile
try user.save()
try SendUser.sendUser(user: user)
} catch {
print("Fetch details faield")
}
}
return accessToken
}
func user(request: Request) throws -> ResponseRepresentable {
guard let email = request.data["email"]?.string else {
throw Abort.custom(status: .badRequest, message: "Parameter email:string is required")
}
let accessToken = UUID().uuidString
return fetchUser(email: email, accessToken: accessToken)
}
func verifyUser(idToken: String) throws -> (String, String) {
let response = try drop.client.get("https://www.googleapis.com/oauth2/v3/tokeninfo?" +
"id_token=\(idToken)")
guard let bytes = response.body.bytes, let body = try? JSONSerialization.jsonObject(with: Data(bytes: bytes), options: []) else {
throw Abort.custom(status: .badRequest, message: "Failed to parse Google verification response")
}
if let body = body as? [String : String], let userId = body["sub"], let email = body["email"] {
return (userId, email)
} else {
throw Abort.custom(status: .badRequest, message: "Failed to get Google user id")
}
}
func fetchUser(email: String, accessToken: String) -> User {
var user: User
if let users = try? User.query().filter("email", email).run(), let oldUser = users.first {
user = oldUser
user.accessToken = accessToken
} else {
user = User(email: email, accessToken: accessToken)
}
return user
}
func fetchUserProfile(userId: String, user: User) throws -> JSON {
let response = try drop.client.get("https://content.googleapis.com/plus/v1/people/" +
"\(userId)?" +
"key=\(serverKey)")
guard let bytes = response.body.bytes, let _ = try? JSONSerialization.jsonObject(with: Data(bytes: bytes), options: []) else {
throw Abort.custom(status: .badRequest, message: "Failed to parse Google user response")
}
return try JSON(bytes: bytes)
}
}
| mit |
apple/swift-syntax | Tests/SwiftParserTest/translated/EffectfulPropertiesTests.swift | 1 | 10435 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test file has been translated from swift/test/Parse/effectful_properties.swift
import XCTest
final class EffectfulPropertiesTests: XCTestCase {
func testEffectfulProperties1() {
AssertParse(
"""
struct MyProps {
var prop1 : Int {
get async { }
}
var prop2 : Int {
get throws { }
}
var prop3 : Int {
get async throws { }
}
var prop1mut : Int {
mutating get async { }
}
var prop2mut : Int {
mutating get throws { }
}
var prop3mut : Int {
mutating get async throws { }
}
}
"""
)
}
func testEffectfulProperties2() {
AssertParse(
"""
struct X1 {
subscript(_ i : Int) -> Int {
get async {}
}
}
"""
)
}
func testEffectfulProperties3() {
AssertParse(
"""
class X2 {
subscript(_ i : Int) -> Int {
get throws {}
}
}
"""
)
}
func testEffectfulProperties4() {
AssertParse(
"""
struct X3 {
subscript(_ i : Int) -> Int {
get async throws {}
}
}
"""
)
}
func testEffectfulProperties5() {
AssertParse(
"""
struct BadSubscript1 {
subscript(_ i : Int) -> Int {
get async throws {}
set {}
}
}
""",
diagnostics: [
// TODO: Old parser expected error on line 4: 'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'
]
)
}
func testEffectfulProperties6() {
AssertParse(
"""
struct BadSubscript2 {
subscript(_ i : Int) -> Int {
get throws {}
set throws {}
}
}
""",
diagnostics: [
// TODO: Old parser expected error on line 4: 'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'
// TODO: Old parser expected error on line 4: 'set' accessor cannot have specifier 'throws'
]
)
}
func testEffectfulProperties7() {
AssertParse(
"""
struct S {
var prop2 : Int {
mutating get async throws { 0 }
nonmutating set {}
}
}
""",
diagnostics: [
// TODO: Old parser expected error on line 4: 'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'
]
)
}
func testEffectfulProperties8() {
AssertParse(
"""
var prop3 : Bool {
_read { yield prop3 }
// expected-note@+1 2 {{previous definition of getter here}}
get throws { false }
get async { true }
get {}
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: '_read' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'
// TODO: Old parser expected error on line 2: variable cannot provide both a 'read' accessor and a getter
// TODO: Old parser expected note on line 4: getter defined here
// TODO: Old parser expected error on line 5: variable already has a getter
// TODO: Old parser expected error on line 6: variable already has a getter
]
)
}
func testEffectfulProperties9() {
AssertParse(
"""
enum E {
private(set) var prop4 : Double {
set {}
get async throws { 1.1 }
_modify { yield &prop4 }
}
}
""",
diagnostics: [
// TODO: Old parser expected error on line 3: 'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'
// TODO: Old parser expected error on line 5: '_modify' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'
]
)
}
func testEffectfulProperties10() {
AssertParse(
"""
protocol P {
associatedtype T
var prop1 : T { get async throws }
var prop2 : T { get async throws set }
var prop3 : T { get throws set }
var prop4 : T { get async }
var prop5 : T { mutating get async throws }
var prop6 : T { mutating get throws }
var prop7 : T { mutating get async nonmutating set }
}
""",
diagnostics: [
// TODO: Old parser expected error on line 4: 'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'
// TODO: Old parser expected error on line 5: 'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'
// TODO: Old parser expected error on line 9: 'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'
]
)
}
func testEffectfulProperties11() {
AssertParse(
"""
///////////////////
// invalid syntax
"""
)
}
func testEffectfulProperties12() {
AssertParse(
"""
var bad1 : Int {
get rethrows { 0 }
set rethrows { }
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: only function declarations may be marked 'rethrows'; did you mean 'throws'?
// TODO: Old parser expected error on line 3: 'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'
// TODO: Old parser expected error on line 3: 'set' accessor cannot have specifier 'rethrows'
]
)
}
func testEffectfulProperties13() {
AssertParse(
"""
var bad2 : Int {
get reasync { 0 }
set reasync { }
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: expected '{' to start getter definition
]
)
}
func testEffectfulProperties14() {
AssertParse(
"""
var bad3 : Int {
_read async { yield 0 }
set(theValue) async { }
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: '_read' accessor cannot have specifier 'async'
// TODO: Old parser expected error on line 3: 'set' accessor cannot have specifier 'async'
]
)
}
func testEffectfulProperties15() {
AssertParse(
"""
var bad4 : Int = 0 {
willSet(theValue) reasync rethrows 1️⃣async throws {}
didSet throws bogus {}
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: 'willSet' accessor cannot have specifier 'throws'
// TODO: Old parser expected error on line 2: 'willSet' accessor cannot have specifier 'async'
// TODO: Old parser expected error on line 2: 'willSet' accessor cannot have specifier 'rethrows'
// TODO: Old parser expected error on line 2: 'willSet' accessor cannot have specifier 'reasync'
DiagnosticSpec(message: "unexpected code in variable"),
// TODO: Old parser expected error on line 3: expected '{' to start 'didSet' definition
// TODO: Old parser expected error on line 3: 'didSet' accessor cannot have specifier 'throws'
]
)
}
func testEffectfulProperties16() {
AssertParse(
"""
var bad5 : Int {
get 1️⃣bogus rethrows {}
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: expected '{' to start getter definition
DiagnosticSpec(message: "unexpected code 'bogus rethrows {}' in variable"),
]
)
}
func testEffectfulProperties17() {
AssertParse(
"""
var bad6 : Int {
get rethrows 1️⃣-> Int { 0 }
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: expected '{' to start getter definition
// TODO: Old parser expected error on line 2: only function declarations may be marked 'rethrows'; did you mean 'throws'?
DiagnosticSpec(message: "unexpected code '-> Int { 0 }' in variable"),
]
)
}
func testEffectfulProperties18() {
AssertParse(
"""
var bad7 : Double {
get throws async { 3.14 }
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: 'async' must precede 'throws'
]
)
}
func testEffectfulProperties19() {
AssertParse(
"""
var bad8 : Double {
get {}
_modify throws async { yield &bad8 }
}
""",
diagnostics: [
// TODO: Old parser expected error on line 3: '_modify' accessor cannot have specifier 'async'
// TODO: Old parser expected error on line 3: '_modify' accessor cannot have specifier 'throws'
]
)
}
func testEffectfulProperties20() {
AssertParse(
"""
protocol BadP {
var prop2 : Int { get 1️⃣bogus rethrows set }
var prop3 : Int { get rethrows 2️⃣bogus set }
var prop4 : Int { get reasync 3️⃣bogus set }
var prop5 : Int { get throws async }
}
""",
diagnostics: [
// TODO: Old parser expected error on line 2: expected get or set in a protocol property
DiagnosticSpec(locationMarker: "1️⃣", message: "unexpected code 'bogus rethrows set' in variable"),
// TODO: Old parser expected error on line 3: only function declarations may be marked 'rethrows'; did you mean 'throws'?
// TODO: Old parser expected error on line 3: expected get or set in a protocol property
DiagnosticSpec(locationMarker: "2️⃣", message: "unexpected code 'bogus set' in variable"),
// TODO: Old parser expected error on line 4: expected get or set in a protocol property
DiagnosticSpec(locationMarker: "3️⃣", message: "unexpected code 'bogus set' in variable"),
// TODO: Old parser expected error on line 5: 'async' must precede 'throws'
]
)
}
}
| apache-2.0 |
lulee007/GankMeizi | GankMeizi/Search/SearchModel.swift | 1 | 1651 | //
// SearchModel.swift
// GankMeizi
//
// Created by 卢小辉 on 16/5/26.
// Copyright © 2016年 lulee007. All rights reserved.
//
import Foundation
import RxSwift
import CocoaLumberjack
import Kanna
import ObjectMapper
class SearchModel: BaseModel {
static let sharedInstance = SearchModel()
var searchText: String
var items: [ArticleEntity]
override init() {
self.searchText = ""
items = []
super.init()
}
func search(text: String?,category: String = "all",count: Int = 20,page: Int = 1) -> Observable<[ArticleEntity]> {
self.offset = count
if page != 1{
self.page = page
}
if text != nil {
self.searchText = text!
items.removeAll()
self.page = 1
}
return provider.request(GankIOService.Search(text: self.searchText,category: category,count: self.offset,page: self.page))
.observeOn(backgroundWorkScheduler)
.filterStatusCodes(200...201)
.observeOn(backgroundWorkScheduler)
.map { (response) -> [ArticleEntity] in
let jsonStr = String(data: response.data,encoding: NSUTF8StringEncoding)
let result = Mapper<BaseEntity<ArticleEntity>>().map(jsonStr!)
if ((result?.results) != nil){
self.page = self.page + 1
self.items += (result?.results!)!
}
return self.items
}
}
func reset() {
self.page = 1
self.items.removeAll()
}
}
| mit |
lyimin/EyepetizerApp | EyepetizerApp/EyepetizerApp/Controllers/ChoiceController/EYEChoiceController.swift | 1 | 8566 | //
// EYEChoiceController.swift
// EyepetizerApp
//
// Created by 梁亦明 on 16/3/10.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import UIKit
import Alamofire
class EYEChoiceController: EYEBaseViewController, LoadingPresenter, MenuPresenter {
//MARK: --------------------------- LifeCycle --------------------------
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(collectionView)
// 设置loadview
setupLoaderView()
// 获取数据
getData(EYEAPIHeaper.API_Choice, params: ["date" : NSDate.getCurrentTimeStamp(), "num" : "7"])
setLoaderViewHidden(false)
// 初始化菜单按钮
setupMenuBtn()
// 下拉刷新
collectionView.headerViewPullToRefresh { [unowned self] in
self.getData(EYEAPIHeaper.API_Choice, params: ["date": NSDate.getCurrentTimeStamp(), "num": "7"])
}
// 上拉加载更多
collectionView.footerViewPullToRefresh {[unowned self] in
if let url = self.nextPageUrl {
self.getData(url)
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
//MARK: --------------------------- Network --------------------------
private func getData(api: String, params: [String : AnyObject]? = nil) {
Alamofire.request(.GET, api, parameters: params).responseSwiftyJSON ({[unowned self](request, Response, json, error) -> Void in
print("\(EYEAPIHeaper.API_Choice)- \(params)")
if json != .null && error == nil{
// 转模型
let dict = json.rawValue as! NSDictionary
// 获取下一个url
self.nextPageUrl = dict["nextPageUrl"] as? String
// 内容数组
let issueArray = dict["issueList"] as! [NSDictionary]
let list = issueArray.map({ (dict) -> IssueModel in
return IssueModel(dict: dict)
})
// 这里判断下拉刷新还是上拉加载更多,如果是上拉加载更多,拼接model。如果是下拉刷新,直接复制
if let _ = params {
// 如果params有值就是下拉刷新
self.issueList = list
self.collectionView.headerViewEndRefresh()
} else {
self.issueList.appendContentsOf(list)
self.collectionView.footerViewEndRefresh()
}
// 隐藏loaderview
self.setLoaderViewHidden(true)
// 刷新
self.collectionView.reloadData()
}
})
}
//MARK: --------------------------- Event or Action --------------------------
func menuBtnDidClick() {
let menuController = EYEMenuViewController()
menuController.modalPresentationStyle = .Custom
menuController.transitioningDelegate = self
// 设置刀砍式动画属性
if menuController is GuillotineAnimationDelegate {
presentationAnimator.animationDelegate = menuController as? GuillotineAnimationDelegate
}
presentationAnimator.supportView = self.navigationController?.navigationBar
presentationAnimator.presentButton = menuBtn
presentationAnimator.duration = 0.15
self.presentViewController(menuController, animated: true, completion: nil)
}
//MARK: --------------------------- Getter or Setter -------------------------
/// 模型数据
var issueList: [IssueModel] = [IssueModel]()
/// 下一个page的地址
var nextPageUrl: String?
/// 加载控件
var loaderView: EYELoaderView!
/// 菜单按钮
var menuBtn: EYEMenuBtn!
/// collectionView
private lazy var collectionView : EYECollectionView = {
var collectionView : EYECollectionView = EYECollectionView(frame: self.view.bounds, collectionViewLayout:EYECollectionLayout())
// 注册header
collectionView.registerClass(EYEChoiceHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: EYEChoiceHeaderView.reuseIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
// 点击菜单动画
private lazy var presentationAnimator = GuillotineTransitionAnimation()
}
//MARK: --------------------------- UICollectionViewDelegate, UICollectionViewDataSource --------------------------
extension EYEChoiceController : UICollectionViewDelegate, UICollectionViewDataSource {
// return section count
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return issueList.count
}
// return section row count
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let issueModel : IssueModel = issueList[section]
let itemList = issueModel.itemList
return itemList.count
}
// 传递模型
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
let cell = cell as! EYEChoiceCell
let issueModel = issueList[indexPath.section]
cell.model = issueModel.itemList[indexPath.row]
}
// 显示view
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : EYEChoiceCell = collectionView.dequeueReusableCellWithReuseIdentifier(EYEChoiceCell.reuseIdentifier, forIndexPath: indexPath) as! EYEChoiceCell
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.selectCell = collectionView.cellForItemAtIndexPath(indexPath) as! EYEChoiceCell
let issueModel = issueList[indexPath.section]
let model: ItemModel = issueModel.itemList[indexPath.row]
// 如果播放地址为空就返回
if model.playUrl.isEmpty {
APESuperHUD.showOrUpdateHUD(.SadFace, message: "没有播放地址", duration: 0.3, presentingView: self.view, completion: nil)
return
}
self.navigationController?.pushViewController(EYEVideoDetailController(model: model), animated: true)
}
/**
* section HeaderView
*/
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
// if kind == UICollectionElementKindSectionHeader {
let headerView : EYEChoiceHeaderView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: EYEChoiceHeaderView.reuseIdentifier, forIndexPath: indexPath) as! EYEChoiceHeaderView
let issueModel = issueList[indexPath.section]
if let image = issueModel.headerImage {
headerView.image = image
} else {
headerView.title = issueModel.headerTitle
}
return headerView
// }
}
// return section headerview height
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
// 获取cell的类型
let issueModel = issueList[section]
if issueModel.isHaveSectionView {
return CGSize(width: UIConstant.SCREEN_WIDTH, height: 50)
} else {
return CGSizeZero
}
}
}
// 这个是点击菜单的动画代理。
extension EYEChoiceController: UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
presentationAnimator.mode = .Presentation
return presentationAnimator
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
presentationAnimator.mode = .Dismissal
return presentationAnimator
}
} | mit |
skyfe79/RxPlayground | RxSectionedTableView/RxSectionedTableView/NumberSection.swift | 1 | 1412 | //
// NumberSection.swift
// RxSectionedTableView
//
// Created by burt.k(Sungcheol Kim) on 2016. 1. 20..
// Copyright © 2016년 burt. All rights reserved.
//
import Foundation
import RxDataSources
// MARK: Data
struct NumberSection {
var header: String
var numbers: [IntItem]
var updated: NSDate
init(header: String, numbers: [IntItem], updated: NSDate) {
self.header = header
self.numbers = numbers
self.updated = updated
}
}
struct IntItem {
let number: Int
let date: NSDate
}
// MARK: Just extensions to say how to determine identity and how to determine is entity updated
extension NumberSection : AnimatableSectionModelType {
typealias Item = IntItem
typealias Identity = String
var identity: String {
return header
}
var items: [IntItem] {
return numbers
}
init(original: NumberSection, items: [Item]) {
self = original
self.numbers = items
}
}
extension IntItem : IdentifiableType, Equatable {
typealias Identity = Int
var identity: Int {
return number
}
}
func == (lhs: IntItem, rhs: IntItem) -> Bool {
return lhs.number == rhs.number && lhs.date.isEqualToDate(rhs.date)
}
extension IntItem : CustomDebugStringConvertible {
var debugDescription: String {
return "IntItem(number: \(number), data: date)"
}
} | mit |
nathawes/swift | test/Driver/bad_tmpdir.swift | 2 | 840 | // Check a handful of failures in the driver when TMPDIR can't be accessed.
//
// These particular error messages are kind of finicky to hit because they
// depend on what commands the driver needs to execute on each platform, so the
// test is somewhat artificially limited to macOS.
//
// REQUIRES: OS=macosx
// SR-12362: This test is failing on master-next.
// XFAIL: *
// RUN: env TMP="%t/fake/" TMPDIR="%t/fake/" not %target-build-swift -c -driver-filelist-threshold=0 %s 2>&1 | %FileCheck -check-prefix=CHECK-SOURCES %s
// CHECK-SOURCES: - unable to create list of input sources
// RUN: echo > %t.o
// RUN: env TMP="%t/fake/" TMPDIR="%t/fake/" not %target-build-swift -driver-filelist-threshold=0 %t.o 2>&1 | %FileCheck -check-prefix=CHECK-FILELIST %s
// CHECK-FILELIST: - unable to create temporary file for inputs.LinkFileList
| apache-2.0 |
IkeyBenz/Hijack | HighJacked.spritebuilder/Shot.swift | 1 | 456 | //
// Shot.swift
// HighJacked
//
// Created by Ikey Benzaken on 7/13/15.
// Copyright (c) 2015 Apportable. All rights reserved.
//
import Foundation
class Shot: CCNode, CCPhysicsCollisionDelegate {
var hasHit = false
func didLoadFromCCB(){
var delay = CCActionDelay(duration: 0.05)
var callBlock = CCActionCallBlock(block: {self.removeFromParent()})
runAction(CCActionSequence(array: [delay, callBlock]))
}
} | mit |
belkevich/DTModelStorage | DTModelStorage/Utilities/UINib+Existance.swift | 1 | 1776 | //
// UINib+Existance.swift
// DTModelStorageTests
//
// Created by Denys Telezhkin on 15.07.15.
// Copyright (c) 2015 Denys Telezhkin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
public extension UINib {
/// Check whether nib with name exists in bundle
/// - Parameter nibName: Name of xib file
/// - Parameter inBundle: bundle to search in
/// - Returns: true, if nib exists, false - if not.
public class func nibExistsWithNibName(nibName :String,
inBundle bundle: NSBundle = NSBundle.mainBundle()) -> Bool
{
if let _ = bundle.pathForResource(nibName, ofType: "nib")
{
return true
}
return false
}
}
| mit |
belkevich/DTModelStorage | DTModelStorage/Utilities/ModelTransfer.swift | 1 | 1849 | //
// ModelTransfer.swift
// DTModelStorageTests
//
// Created by Denys Telezhkin on 06.07.15.
// Copyright (c) 2015 Denys Telezhkin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/// `ModelTransfer` protocol is used to pass `model` data to your cell or supplementary view. Every cell or supplementary view subclass you have should conform to this protocol.
///
/// - Note: `ModelType` is associated type, that works like generic constraint for specific cell or view. When implementing this method, use model type, that you wish to transfer to cell.
public protocol ModelTransfer
{
/// This is a placeholder for your model type
typealias ModelType
/// Update your view with model
/// - Parameter model: model of ModelType type
func updateWithModel(model : ModelType)
} | mit |
huang1988519/WechatArticles | WechatArticles/WechatArticles/Library/JLToast/JLToast.swift | 2 | 4140 | /*
* JLToast.swift
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* Version 2, December 2004
*
* Copyright (C) 2013-2015 Su Yeol Jeon
*
* Everyone is permitted to copy and distribute verbatim or modified
* copies of this license document, and changing it is allowed as long
* as the name is changed.
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE FUCK YOU WANT TO.
*
*/
import UIKit
public struct JLToastDelay {
public static let ShortDelay: NSTimeInterval = 2.0
public static let LongDelay: NSTimeInterval = 3.5
}
@objc public class JLToast: NSOperation {
public var view: JLToastView = JLToastView()
public var text: String? {
get {
return self.view.textLabel.text
}
set {
self.view.textLabel.text = newValue
}
}
public var delay: NSTimeInterval = 0
public var duration: NSTimeInterval = JLToastDelay.ShortDelay
private var _executing = false
override public var executing: Bool {
get {
return self._executing
}
set {
self.willChangeValueForKey("isExecuting")
self._executing = newValue
self.didChangeValueForKey("isExecuting")
}
}
private var _finished = false
override public var finished: Bool {
get {
return self._finished
}
set {
self.willChangeValueForKey("isFinished")
self._finished = newValue
self.didChangeValueForKey("isFinished")
}
}
internal var window: UIWindow {
let windows = UIApplication.sharedApplication().windows
for window in windows.reverse() {
let className = NSStringFromClass(window.dynamicType)
if className == "UIRemoteKeyboardWindow" || className == "UITextEffectsWindow" {
return window
}
}
return windows.first!
}
public class func makeText(text: String) -> JLToast {
return JLToast.makeText(text, delay: 0, duration: JLToastDelay.ShortDelay)
}
public class func makeText(text: String, duration: NSTimeInterval) -> JLToast {
return JLToast.makeText(text, delay: 0, duration: duration)
}
public class func makeText(text: String, delay: NSTimeInterval, duration: NSTimeInterval) -> JLToast {
let toast = JLToast()
toast.text = text
toast.delay = delay
toast.duration = duration
return toast
}
public func show() {
JLToastCenter.defaultCenter().addToast(self)
}
override public func start() {
if !NSThread.isMainThread() {
dispatch_async(dispatch_get_main_queue(), {
self.start()
})
} else {
super.start()
}
}
override public func main() {
self.executing = true
dispatch_async(dispatch_get_main_queue(), {
self.view.updateView()
self.view.alpha = 0
self.window.addSubview(self.view)
UIView.animateWithDuration(
0.5,
delay: self.delay,
options: .BeginFromCurrentState,
animations: {
self.view.alpha = 1
},
completion: { completed in
UIView.animateWithDuration(
self.duration,
animations: {
self.view.alpha = 1.0001
},
completion: { completed in
self.finish()
UIView.animateWithDuration(0.5, animations: {
self.view.alpha = 0
})
}
)
}
)
})
}
public func finish() {
self.executing = false
self.finished = true
}
} | apache-2.0 |
practicalswift/swift | stdlib/public/core/Availability.swift | 9 | 1711 | //===----------------------------------------------------------------------===//
//
// 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
/// Returns 1 if the running OS version is greater than or equal to
/// major.minor.patchVersion and 0 otherwise.
///
/// This is a magic entry point known to the compiler. It is called in
/// generated code for API availability checking.
@_semantics("availability.osversion")
@inlinable
public func _stdlib_isOSVersionAtLeast(
_ major: Builtin.Word,
_ minor: Builtin.Word,
_ patch: Builtin.Word
) -> Builtin.Int1 {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
if Int(major) == 9999 {
return true._value
}
// The call to _swift_stdlib_operatingSystemVersion is used as an indicator
// that this function was called by a compiler optimization pass. If it is
// replaced that pass needs to be updated.
let runningVersion = _swift_stdlib_operatingSystemVersion()
let result =
(runningVersion.majorVersion,runningVersion.minorVersion,runningVersion.patchVersion)
>= (Int(major),Int(minor),Int(patch))
return result._value
#else
// FIXME: As yet, there is no obvious versioning standard for platforms other
// than Darwin-based OSes, so we just assume false for now.
// rdar://problem/18881232
return false._value
#endif
}
| apache-2.0 |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Protocols/DrawerRouting.swift | 1 | 279 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public protocol DrawerRouting: AnyObject {
/// Closes or open the side menu, depending on its current state
func toggleSideMenu()
/// Closes the side menu
func closeSideMenu()
}
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureCardPayment/Sources/FeatureCardPaymentDomain/Client/CardDeletionClientAPI.swift | 1 | 224 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
public protocol CardDeletionClientAPI: AnyObject {
func deleteCard(by id: String) -> AnyPublisher<Void, NabuNetworkError>
}
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureKYC/Tests/FeatureKYCUITests/Mock/MockKYCEnterPhoneNumberView.swift | 1 | 954 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import FeatureKYCUI
import XCTest
class MockKYCConfirmPhoneNumberView: KYCConfirmPhoneNumberView {
var didCallShowLoadingViewExpectation: XCTestExpectation?
var didCallStartVerifSuccessExpectation: XCTestExpectation?
var didCallShowErrorExpectation: XCTestExpectation?
var didCallHideLoadingViewExpectation: XCTestExpectation?
var didCallConfirmCodeExpectation: XCTestExpectation?
func showLoadingView(with text: String) {
didCallShowLoadingViewExpectation?.fulfill()
}
func startVerificationSuccess() {
didCallStartVerifSuccessExpectation?.fulfill()
}
func showError(message: String) {
didCallShowErrorExpectation?.fulfill()
}
func hideLoadingView() {
didCallHideLoadingViewExpectation?.fulfill()
}
func confirmCodeSuccess() {
didCallConfirmCodeExpectation?.fulfill()
}
}
| lgpl-3.0 |
proxpero/Placeholder | Placeholder/UserProfileViewController.swift | 1 | 2277 |
import UIKit
import CoreLocation
import MapKit
final class UserProfileViewController: UIViewController {
// MARK: IB Outlets & Actions.
@IBOutlet var nameLabel: UILabel!
@IBOutlet var usernameLabel: UILabel!
@IBOutlet var emailLabel: UILabel!
@IBOutlet var streetLabel: UILabel!
@IBOutlet var suiteLabel: UILabel!
@IBOutlet var cityLabel: UILabel!
@IBOutlet var zipcodeLabel: UILabel!
@IBOutlet var mapView: MKMapView!
@IBAction func didTapDone(_ sender: Any) {
dismiss()
}
// MARK: Stored Properties.
/// The `User` to be displayed.
var user: User? {
didSet {
refresh()
}
}
/// Action to dismiss the ViewController.
var dismiss: () -> () = {}
// MARK: Lifecycle
private func refresh() {
if
let nameLabel = nameLabel,
let usernameLabel = usernameLabel,
let emailLabel = emailLabel,
let streetLabel = streetLabel,
let suiteLabel = suiteLabel,
let cityLabel = cityLabel,
let zipcodeLabel = zipcodeLabel,
let mapView = mapView
{
nameLabel.text = user?.name
usernameLabel.text = user?.username
emailLabel.text = user?.email
streetLabel.text = user?.address.street
suiteLabel.text = user?.address.suite
cityLabel.text = user?.address.city
zipcodeLabel.text = user?.address.zipcode
if let location = user?.address.geo.location {
// Some of these coordinates are in the middle of the ocean, so make the region large.
let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 30_000, 30_000)
mapView.setRegion(region, animated: true)
}
}
}
// Refresh the UI in case the models are set before the views exist.
override func viewDidLoad() {
super.viewDidLoad()
refresh()
}
}
extension User.Address.Geo {
/// The CLLocation of the address of the user's address
var location: CLLocation? {
guard let lat = Double(lat), let lng = Double(lng) else { return nil }
return CLLocation(latitude: lat, longitude: lng)
}
}
| mit |
jopamer/swift | test/PCMacro/didset.swift | 1 | 1306 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -Xfrontend -pc-macro -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift %S/Inputs/SilentPlaygroundsRuntime.swift
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: executable_test
// FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode
// UNSUPPORTED: OS=linux-gnu
#sourceLocation(file: "main.swift", line: 10)
struct S {
var a : [Int] = [] {
didSet {
print("Set")
}
}
}
var s = S()
s.a = [3,2]
s.a.append(300)
// CHECK: [18:1-18:12] pc before
// CHECK-NEXT: [18:1-18:12] pc after
// CHECK-NEXT: [19:1-19:12] pc before
// CHECK-NEXT: [12:9-12:15] pc before
// CHECK-NEXT: [12:9-12:15] pc after
// CHECK-NEXT: [13:13-13:25] pc before
// CHECK-NEXT: Set
// CHECK-NEXT: [13:13-13:25] pc after
// CHECK-NEXT: [19:1-19:12] pc after
// CHECK-NEXT: [20:1-20:16] pc before
// CHECK-NEXT: [12:9-12:15] pc before
// CHECK-NEXT: [12:9-12:15] pc after
// CHECK-NEXT: [13:13-13:25] pc before
// CHECK-NEXT: Set
// CHECK-NEXT: [13:13-13:25] pc after
// CHECK-NEXT: [20:1-20:16] pc after
| apache-2.0 |
iOSWizards/AwesomeMedia | Example/AwesomeMedia/Controllers/ViewController.swift | 1 | 12126 | //
// TableViewController.swift
// AwesomeMedia_Example
//
// Created by Evandro Harrison Hoffmann on 4/4/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
import AwesomeMedia
enum MediaType: String {
case video
case audio
case file
case image
case youtube
case verticalVideo
}
struct MediaCell {
var type = MediaType.video
var mediaParams = AwesomeMediaParams()
}
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
// Testing Variables
public static let testVideoURL2 = "http://overmind2.mindvalleyacademy.com/api/v1/assets/cb19bc38-d804-4c30-b1f1-79d28d9d71d4.m3u8"
public static let testVideoURL3 = "http://overmind2.mindvalleyacademy.com/api/v1/assets/b78856cc-d0f0-4069-b1e1-9dbbe47b4df6.m3u8"
public static let testMediaMarkers = [AwesomeMediaMarker(title: "Intro", time: 120),
AwesomeMediaMarker(title: "About WildFit", time: 360),
AwesomeMediaMarker(title: "Day 1", time: 420),
AwesomeMediaMarker(title: "Test Marker 1", time: 422),
AwesomeMediaMarker(title: "Test Marker 2", time: 424),
AwesomeMediaMarker(title: "Test Marker 3", time: 426),
AwesomeMediaMarker(title: "Test Marker 4", time: 428),
AwesomeMediaMarker(title: "Test Marker 5", time: 430),
AwesomeMediaMarker(title: "Test Marker 6", time: 440),
AwesomeMediaMarker(title: "Test Marker 7", time: 441)]
public static let testAudioURL = "https://archive.org/download/VirtualHaircut/virtualbarbershop.mp3"
public static let testPDFURL = "https://www.paloaltonetworks.com/content/dam/pan/en_US/assets/pdf/datasheets/wildfire/wildfire-ds.pdf"
let cells: [MediaCell] = [
// MediaCell(type: .video,
// mediaParams: AwesomeMediaParams(
// url: "https://overmind2.mvstg.com/api/v1/assets/7cdddc7f-7344-4eee-8f05-eaeb49cc11ec.m3u8",
// coverUrl: "https://thumbs.dreamstime.com/z/awesome-word-cloud-explosion-background-51481417.jpg",
// author: "John",
// title: "Caption test",
// duration: 20,
// markers: testMediaMarkers,
// params: ["id":"123",
// AwesomeMediaParamsKey.autoplay.rawValue: true,
// AwesomeMediaParamsKey.startOnTime.rawValue: Double(10)])),
// MediaCell(type: .video,
// mediaParams: AwesomeMediaParams(
// url: "https://overmind2.mvstg.com/api/v1/assets/86f21617-6c69-40ef-9cca-d927bf737de1.m3u8",
// coverUrl: "https://cdn.wccftech.com/wp-content/uploads/2017/05/subtitle-of-a-blu-ray-movie.jpg",
// author: "John",
// title: "Caption test 2",
// duration: 20,
// markers: testMediaMarkers,
// params: ["id":"123"])),
MediaCell(type: .audio,
mediaParams: AwesomeMediaParams(
url: testAudioURL,
coverUrl: "https://i.ytimg.com/vi/fwLuHqMMonc/0.jpg",
author: "The barber",
title: "Virtual Barbershop",
duration: 232,
size: "2 mb",
params: ["id":"45"])),
// MediaCell(type: .file,
// mediaParams: AwesomeMediaParams(
// url: testPDFURL,
// coverUrl: "https://i0.wp.com/res.cloudinary.com/changethatmind/image/upload/v1501884914/wildfitsales.png?fit=500%2C500&ssl=1",
// author: "Eric Mendez",
// title: "Wildfit",
// size: "2 mb",
// type: "PDF",
// params: ["id":"45"])),
// MediaCell(type: .image,
// mediaParams: AwesomeMediaParams(
// coverUrl: "https://www.awesometlv.co.il/wp-content/uploads/2016/01/awesome_logo-01.png")),
// /*MediaCell(type: .video,
// mediaParams: AwesomeMediaParams(
// url: testVideoURL,
// coverUrl: "https://i0.wp.com/res.cloudinary.com/changethatmind/image/upload/v1501884914/wildfitsales.png?fit=500%2C500&ssl=1",
// author: "Eric Mendez",
// title: "WildFit 2",
// duration: 12312,
// markers: testMediaMarkers,
// params: ["id":"45"])),*/
// MediaCell(type: .image,
// mediaParams: AwesomeMediaParams(
// coverUrl: "https://i0.wp.com/res.cloudinary.com/changethatmind/image/upload/v1501884914/wildfitsales.png?fit=500%2C500&ssl=1")),
// MediaCell(type: .video,
// mediaParams: AwesomeMediaParams(
// url: "https://overmind2.mvstg.com/api/v1/assets/0892a82b-a9ad-4069-a5b6-cf2e6103267c.m3u8",
// coverUrl: "https://thumbs.dreamstime.com/z/awesome-word-cloud-explosion-background-51481417.jpg",
// author: "Eric Mendez",
// title: "WildFit 3",
// duration: 33222,
// markers: testMediaMarkers,
// params: ["id":"45"])),
// MediaCell(type: .youtube,
// mediaParams: AwesomeMediaParams(
// youtubeUrl: "https://www.youtube.com/watch?v=5WOxJ9rvU1s&t=3s",
// coverUrl: "https://i0.wp.com/res.cloudinary.com/changethatmind/image/upload/v1501884914/wildfitsales.png?fit=500%2C500&ssl=1")),
// MediaCell(type: .youtube,
// mediaParams: AwesomeMediaParams(
// youtubeUrl: "https://www.youtube.com/watch?v=5WOxJ9rvU1s&t=3s",
// coverUrl: "https://i0.wp.com/res.cloudinary.com/changethatmind/image/upload/v1501884914/wildfitsales.png?fit=500%2C500&ssl=1")),
// MediaCell(type: .verticalVideo,
// mediaParams: AwesomeMediaParams(
// url: testAudioURL,
// coverUrl: "https://i.ytimg.com/vi/BiRED7kH-nQ/maxresdefault.jpg",
// backgroundUrl: "https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4",
// author: "Brett Ninja",
// authorAvatar: "https://thumbs.dreamstime.com/z/awesome-word-cloud-explosion-background-51481417.jpg",
// title: "Pushing the Senses",
// about: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
// duration: 20,
// shouldShowMiniPlayer: true,
// sharingItems: ["jajajaja...."],
// favourited: true))
]
var mediaParamsArray: [AwesomeMediaParams] {
var mediaParamsArray = [AwesomeMediaParams]()
for cell in cells {
mediaParamsArray.append(cell.mediaParams)
}
return mediaParamsArray
}
override func viewDidLoad() {
super.viewDidLoad()
// register cells
AwesomeMediaHelper.registerCells(forTableView: tableView)
// set default orientation
awesomeMediaOrientation = .portrait
// add observers
addObservers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
AwesomeMediaHelper.stopIfNeeded()
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return awesomeMediaOrientation
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
handleOrientationChange(withMediaParams: mediaParamsArray)
}
}
// MARK: - Table view data source
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cells.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cells[indexPath.row].type.rawValue, for: indexPath)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let cell = cell as? AwesomeMediaVideoTableViewCell {
cell.configure(withMediaParams: cells[indexPath.row].mediaParams,
widthControls: .fullscreen,
fullScreenControls: .minimize,
fullScreenTitleViewVisible: false)
} else if let cell = cell as? AwesomeMediaAudioTableViewCell {
cell.configure(withMediaParams: cells[indexPath.row].mediaParams)
} else if let cell = cell as? AwesomeMediaFileTableViewCell {
cell.configure(withMediaParams: cells[indexPath.row].mediaParams)
} else if let cell = cell as? AwesomeMediaImageTableViewCell {
cell.configure(withMediaParams: cells[indexPath.row].mediaParams)
} else if let cell = cell as? AwesomeMediaYoutubeTableViewCell {
cell.configure(withMediaParams: cells[indexPath.row].mediaParams)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch cells[indexPath.row].type {
case .audio:
return AwesomeMediaAudioTableViewCell.defaultSize.height
case .video:
return AwesomeMediaVideoTableViewCell.defaultSize.height
case .file:
return AwesomeMediaFileTableViewCell.defaultSize.height
case .image:
return AwesomeMediaImageTableViewCell.size(withTableView: tableView, indexPath: indexPath).height
case .youtube:
return AwesomeMediaYoutubeTableViewCell.defaultSize.height
case .verticalVideo:
return AwesomeMediaVideoTableViewCell.defaultSize.height
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if cells[indexPath.row].type == .verticalVideo {
presentVerticalVideoFullscreen(withMediaParams: cells[indexPath.row].mediaParams)
}
}
}
extension UIViewController: AwesomeMediaEventObserver {
public func addObservers() {
AwesomeMediaNotificationCenter.addObservers([.showMiniPlayer, .hideMiniPlayer], to: self)
}
public func removeObservers() {
AwesomeMediaNotificationCenter.removeObservers(from: self)
}
public func showMiniPlayer(_ notification: NSNotification) {
if let params = notification.object as? AwesomeMediaParams {
_ = view.addAudioPlayer(withParams: params, animated: true)
} else {
view.removeAudioControlView(animated: true)
}
}
public func hideMiniPlayer(_ notification: NSNotification) {
view.removeAudioControlView(animated: true)
}
}
| mit |
huonw/swift | validation-test/Serialization/Inputs/serialization_loops_helper.swift | 70 | 92 | import Foundation
open class Sub : Base {
public override init() {
print("hi")
}
}
| apache-2.0 |
huonw/swift | validation-test/StdlibUnittest/Filter.swift | 33 | 969 | // RUN: %target-build-swift %s -o %t.out
// RUN: %target-run %t.out --stdlib-unittest-filter abc | %FileCheck --check-prefix=CHECK-ABC %s
// RUN: %target-run %t.out --stdlib-unittest-filter xyz | %FileCheck --check-prefix=CHECK-XYZ %s
// CHECK-ABC: StdlibUnittest: using filter: abc{{$}}
// CHECK-ABC: [ RUN ] Filter.abc{{$}}
// CHECK-ABC: [ OK ] Filter.abc{{$}}
// CHECK-ABC: [ RUN ] Filter.abcdef{{$}}
// CHECK-ABC: [ OK ] Filter.abcdef{{$}}
// CHECK-ABC-NOT: xyz
// CHECK-XYZ: StdlibUnittest: using filter: xyz{{$}}
// CHECK-XYZ-NOT: abc
// CHECK-XYZ: [ RUN ] Filter.xyz{{$}}
// REQUIRES: executable_test
// CHECK-XYZ: [ OK ] Filter.xyz{{$}}
// CHECK-XYZ-NOT: abc
// CHECK-XYZ-NOT: xyz
import StdlibUnittest
var FilterTestSuite = TestSuite("Filter")
FilterTestSuite.test("abc") {
expectEqual(1, 1)
}
FilterTestSuite.test("abcdef") {
expectEqual(1, 1)
}
FilterTestSuite.test("xyz") {
expectEqual(1, 1)
}
runAllTests()
| apache-2.0 |
ObjectAlchemist/OOUIKit | Sources/View/Positioning/ViewStackVertical.swift | 1 | 2526 | //
// ViewStackVertical.swift
// OOSwift
//
// Created by Karsten Litsche on 01.09.17.
//
//
import UIKit
public let VerticalStretched: Float = -1
/**
A view container that presents it's contents in a vertical top based stack.
Note: Last view ignores it's height and stretches to end (use VerticalStretched to tell)! Add a VrSpace at end if you don't like it.
Visual:
---
<content1>
<content2>
^
content3 (height=VerticalStretched)
v
---
*/
public final class ViewStackVertical: OOView {
// MARK: init
public init(content childs: [(height: Float, view: OOView)]) {
guard childs.count != 0 else { fatalError("A container without childs doesn't make any sense!") }
guard childs.filter( { $0.height == VerticalStretched }).count == 1 else { fatalError("A stack must contain exactly one child with height=VerticalStretched!") }
self.childs = childs
}
// MARK: protocol OOView
private var _ui: UIView?
public var ui: UIView {
if _ui == nil { _ui = createView() }
return _ui!
}
public func setNeedsRefresh() {
childs.forEach { $0.view.setNeedsRefresh() }
}
// MARK: private
private let childs: [(height: Float, view: OOView)]
private func createView() -> UIView {
let view = PointInsideCheckingView()
view.backgroundColor = UIColor.clear
addChilds(toView: view)
return view
}
private func addChilds(toView parentView: UIView) {
let last = childs.last!.view
var previousChild: UIView?
childs.forEach { (height: Float, view: OOView) in
let childView = view.ui
childView.translatesAutoresizingMaskIntoConstraints = false
parentView.addSubview(childView)
childView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true
childView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true
childView.topAnchor.constraint(equalTo: previousChild==nil ? parentView.topAnchor : previousChild!.bottomAnchor).isActive = true
if last === view {
childView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true
}
if height != VerticalStretched {
childView.heightAnchor.constraint(equalToConstant: CGFloat(height)).isActive = true
}
previousChild = childView
}
}
}
| mit |
JaSpa/swift | validation-test/compiler_crashers/28656-unreachable-executed-at-swift-lib-ast-type-cpp-1137.swift | 4 | 443 | // 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 --crash %target-swift-frontend %s -emit-ir
{ struct A{
p.init(UInt=1 + 1 as?Int){
| apache-2.0 |
gustavoavena/BandecoUnicamp | BandecoUnicamp/Cache.swift | 1 | 633 | //
// Cache.swift
// BandecoUnicamp
//
// Created by Gustavo Avena on 24/07/17.
// Copyright © 2017 Gustavo Avena. All rights reserved.
//
import UIKit
protocol CacheObserver {
func newData()
}
class Cache: NSObject {
private static var sharedCache: Cache = {
let cache = Cache()
return cache
}()
class func shared() -> Cache {
return sharedCache
}
public var cardapios: [Cardapio]
public var observers: [CacheObserver]
private override init() {
self.cardapios = [Cardapio]()
self.observers = [CacheObserver]()
}
}
| mit |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/Asset.swift | 1 | 564 | //
// Asset.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/9/19.
//
import Foundation
public class Asset: Codable {
/// The ID of the asset
let id: String
private enum CodingKeys : String, CodingKey {
case id = "id"
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Asset.CodingKeys.self)
if let id = try? container.decode(String.self, forKey: .id) {
self.id = id
} else {
self.id = String(try container.decode(Int.self, forKey: .id))
}
}
}
| mit |
bizz84/MVHorizontalPicker | MVHorizontalPickerDemo/AppDelegate.swift | 1 | 3140 | /*
MVHorizontalPicker - Copyright (c) 2016 Andrea Bizzotto bizz84@gmail.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
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> 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 |
Fitbit/RxBluetoothKit | ExampleApp/ExampleApp/Screens/CentralSpecific/CentralSpecificView.swift | 2 | 1835 | import UIKit
class CentralSpecificView: UIView {
init() {
super.init(frame: .zero)
backgroundColor = .systemBackground
setupLayout()
}
required init?(coder: NSCoder) { nil }
// MARK: - Subviews
let serviceUuidTextField: UITextField = {
let textField = UITextField()
textField.placeholder = Labels.serviceUuidPlaceholder
return textField
}()
let characteristicUuidTextField: UITextField = {
let textField = UITextField()
textField.placeholder = Labels.characteristicUuidPlaceholder
return textField
}()
let connectButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Connect", for: .normal)
button.setImage(UIImage(systemName: "bolt.horizontal"), for: .normal)
return button
}()
let readValueLabel: UILabel = {
let label = UILabel()
label.text = "Read value: --"
label.font = UIFont.systemFont(ofSize: 20.0)
label.textColor = .green
return label
}()
let stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = 20.0
return stackView
}()
// MARK: - Private
private func setupLayout() {
stackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(stackView)
[serviceUuidTextField, characteristicUuidTextField,
connectButton, readValueLabel].forEach(stackView.addArrangedSubview)
NSLayoutConstraint.activate([
stackView.centerXAnchor.constraint(equalTo: centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: centerYAnchor),
stackView.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, constant: -32)
])
}
}
| apache-2.0 |
maxoly/PulsarKit | PulsarKitExample/PulsarKitExample/Controllers/Basic/Insert/InsertSectionsViewController.swift | 1 | 370 | //
// InsertSectionsViewController.swift
// PulsarKitExample
//
// Created by Massimo Oliviero on 29/01/2021.
// Copyright © 2021 Nacoon. All rights reserved.
//
import UIKit
import PulsarKit
final class InsertSectionsViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Add/insert sections"
}
}
| mit |
Makosa/BubbleControl-Swift | BubbleControl-Swift/ViewController.swift | 1 | 14060 | //
// ViewController.swift
// BubbleControl-Swift
//
// Created by Cem Olcay on 11/12/14.
// Copyright (c) 2014 Cem Olcay. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupBubble()
}
// MARK: Bubble
var bubble: BubbleControl!
func setupBubble () {
let win = APPDELEGATE.window!
bubble = BubbleControl (size: CGSizeMake(80, 80))
bubble.image = UIImage (named: "basket.png")
bubble.didNavigationBarButtonPressed = {
println("pressed in nav bar")
self.bubble!.popFromNavBar()
}
bubble.setOpenAnimation = { content, background in
self.bubble.contentView!.bottom = win.bottom
if (self.bubble.center.x > win.center.x) {
self.bubble.contentView!.left = win.right
self.bubble.contentView!.spring({ () -> Void in
self.bubble.contentView!.right = win.right
}, completion: nil)
} else {
self.bubble.contentView!.right = win.left
self.bubble.contentView!.spring({ () -> Void in
self.bubble.contentView!.left = win.left
}, completion: nil)
}
}
let min: CGFloat = 50
let max: CGFloat = win.h - 250
let randH = min + CGFloat(random()%Int(max-min))
let v = UIView (frame: CGRect (x: 0, y: 0, width: win.w, height: max))
v.backgroundColor = UIColor.grayColor()
let label = UILabel (frame: CGRect (x: 10, y: 10, width: v.w, height: 20))
label.text = "test text"
v.addSubview(label)
bubble.contentView = v
win.addSubview(bubble)
}
// MARK: Animation
var animateIcon: Bool = false {
didSet {
if animateIcon {
bubble.didToggle = { on in
if let shapeLayer = self.bubble.imageView?.layer.sublayers?[0] as? CAShapeLayer {
self.animateBubbleIcon(on)
}
else {
self.bubble.imageView?.image = nil
let shapeLayer = CAShapeLayer ()
shapeLayer.lineWidth = 0.25
shapeLayer.strokeColor = UIColor.blackColor().CGColor
shapeLayer.fillMode = kCAFillModeForwards
self.bubble.imageView?.layer.addSublayer(shapeLayer)
self.animateBubbleIcon(on)
}
}
} else {
bubble.didToggle = nil
bubble.imageView?.layer.sublayers = nil
bubble.imageView?.image = bubble.image!
}
}
}
func animateBubbleIcon (on: Bool) {
let shapeLayer = self.bubble.imageView!.layer.sublayers![0] as! CAShapeLayer
let from = on ? self.basketBezier().CGPath: self.arrowBezier().CGPath
let to = on ? self.arrowBezier().CGPath: self.basketBezier().CGPath
let anim = CABasicAnimation (keyPath: "path")
anim.fromValue = from
anim.toValue = to
anim.duration = 0.5
anim.fillMode = kCAFillModeForwards
anim.removedOnCompletion = false
shapeLayer.addAnimation (anim, forKey:"bezier")
}
func arrowBezier () -> UIBezierPath {
//// PaintCode Trial Version
//// www.paintcodeapp.com
let color0 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
var bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(21.22, 2.89))
bezier2Path.addCurveToPoint(CGPointMake(19.87, 6.72), controlPoint1: CGPointMake(21.22, 6.12), controlPoint2: CGPointMake(20.99, 6.72))
bezier2Path.addCurveToPoint(CGPointMake(14.54, 7.92), controlPoint1: CGPointMake(19.12, 6.72), controlPoint2: CGPointMake(16.72, 7.24))
bezier2Path.addCurveToPoint(CGPointMake(0.44, 25.84), controlPoint1: CGPointMake(7.27, 10.09), controlPoint2: CGPointMake(1.64, 17.14))
bezier2Path.addCurveToPoint(CGPointMake(2.39, 26.97), controlPoint1: CGPointMake(-0.08, 29.74), controlPoint2: CGPointMake(1.12, 30.49))
bezier2Path.addCurveToPoint(CGPointMake(17.62, 16.09), controlPoint1: CGPointMake(4.34, 21.19), controlPoint2: CGPointMake(10.12, 17.14))
bezier2Path.addLineToPoint(CGPointMake(21.14, 15.64))
bezier2Path.addLineToPoint(CGPointMake(21.37, 19.47))
bezier2Path.addLineToPoint(CGPointMake(21.59, 23.29))
bezier2Path.addLineToPoint(CGPointMake(29.09, 17.52))
bezier2Path.addCurveToPoint(CGPointMake(36.59, 11.22), controlPoint1: CGPointMake(33.22, 14.37), controlPoint2: CGPointMake(36.59, 11.52))
bezier2Path.addCurveToPoint(CGPointMake(22.12, -0.33), controlPoint1: CGPointMake(36.59, 10.69), controlPoint2: CGPointMake(24.89, 1.39))
bezier2Path.addCurveToPoint(CGPointMake(21.22, 2.89), controlPoint1: CGPointMake(21.44, -0.71), controlPoint2: CGPointMake(21.22, 0.19))
bezier2Path.closePath()
bezier2Path.moveToPoint(CGPointMake(31.87, 8.82))
bezier2Path.addCurveToPoint(CGPointMake(34.64, 11.22), controlPoint1: CGPointMake(33.44, 9.94), controlPoint2: CGPointMake(34.72, 10.99))
bezier2Path.addCurveToPoint(CGPointMake(28.87, 15.87), controlPoint1: CGPointMake(34.64, 11.44), controlPoint2: CGPointMake(32.09, 13.54))
bezier2Path.addLineToPoint(CGPointMake(23.09, 20.14))
bezier2Path.addLineToPoint(CGPointMake(22.87, 17.07))
bezier2Path.addLineToPoint(CGPointMake(22.64, 13.99))
bezier2Path.addLineToPoint(CGPointMake(18.97, 14.44))
bezier2Path.addCurveToPoint(CGPointMake(6.22, 19.24), controlPoint1: CGPointMake(13.04, 15.12), controlPoint2: CGPointMake(9.44, 16.54))
bezier2Path.addCurveToPoint(CGPointMake(5.09, 16.84), controlPoint1: CGPointMake(2.77, 22.24), controlPoint2: CGPointMake(2.39, 21.49))
bezier2Path.addCurveToPoint(CGPointMake(20.69, 8.22), controlPoint1: CGPointMake(8.09, 11.82), controlPoint2: CGPointMake(14.54, 8.22))
bezier2Path.addCurveToPoint(CGPointMake(22.72, 5.14), controlPoint1: CGPointMake(22.57, 8.22), controlPoint2: CGPointMake(22.72, 7.99))
bezier2Path.addLineToPoint(CGPointMake(22.72, 2.07))
bezier2Path.addLineToPoint(CGPointMake(25.94, 4.47))
bezier2Path.addCurveToPoint(CGPointMake(31.87, 8.82), controlPoint1: CGPointMake(27.67, 5.74), controlPoint2: CGPointMake(30.37, 7.77))
bezier2Path.closePath()
bezier2Path.miterLimit = 4;
color0.setFill()
bezier2Path.fill()
return bezier2Path
}
func basketBezier () -> UIBezierPath {
//// PaintCode Trial Version
//// www.paintcodeapp.com
let color0 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
var bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(0.86, 0.36))
bezier2Path.addCurveToPoint(CGPointMake(3.41, 6.21), controlPoint1: CGPointMake(-0.27, 1.41), controlPoint2: CGPointMake(0.48, 2.98))
bezier2Path.addLineToPoint(CGPointMake(6.41, 9.51))
bezier2Path.addLineToPoint(CGPointMake(3.18, 9.73))
bezier2Path.addCurveToPoint(CGPointMake(-0.27, 12.96), controlPoint1: CGPointMake(0.03, 9.96), controlPoint2: CGPointMake(-0.04, 10.03))
bezier2Path.addCurveToPoint(CGPointMake(0.48, 16.71), controlPoint1: CGPointMake(-0.42, 14.83), controlPoint2: CGPointMake(-0.12, 16.18))
bezier2Path.addCurveToPoint(CGPointMake(3.26, 23.46), controlPoint1: CGPointMake(1.08, 17.08), controlPoint2: CGPointMake(2.28, 20.16))
bezier2Path.addCurveToPoint(CGPointMake(18.33, 32.08), controlPoint1: CGPointMake(6.03, 32.91), controlPoint2: CGPointMake(4.61, 32.08))
bezier2Path.addCurveToPoint(CGPointMake(33.41, 23.46), controlPoint1: CGPointMake(32.06, 32.08), controlPoint2: CGPointMake(30.63, 32.91))
bezier2Path.addCurveToPoint(CGPointMake(36.18, 16.71), controlPoint1: CGPointMake(34.38, 20.16), controlPoint2: CGPointMake(35.58, 17.08))
bezier2Path.addCurveToPoint(CGPointMake(36.93, 12.96), controlPoint1: CGPointMake(36.78, 16.18), controlPoint2: CGPointMake(37.08, 14.83))
bezier2Path.addCurveToPoint(CGPointMake(33.48, 9.73), controlPoint1: CGPointMake(36.71, 10.03), controlPoint2: CGPointMake(36.63, 9.96))
bezier2Path.addLineToPoint(CGPointMake(30.26, 9.51))
bezier2Path.addLineToPoint(CGPointMake(33.33, 6.13))
bezier2Path.addCurveToPoint(CGPointMake(36.18, 1.48), controlPoint1: CGPointMake(35.06, 4.26), controlPoint2: CGPointMake(36.33, 2.16))
bezier2Path.addCurveToPoint(CGPointMake(28.23, 4.63), controlPoint1: CGPointMake(35.66, -1.22), controlPoint2: CGPointMake(33.26, -0.24))
bezier2Path.addLineToPoint(CGPointMake(23.06, 9.58))
bezier2Path.addLineToPoint(CGPointMake(18.33, 9.58))
bezier2Path.addLineToPoint(CGPointMake(13.61, 9.58))
bezier2Path.addLineToPoint(CGPointMake(8.51, 4.71))
bezier2Path.addCurveToPoint(CGPointMake(0.86, 0.36), controlPoint1: CGPointMake(3.78, 0.13), controlPoint2: CGPointMake(2.06, -0.84))
bezier2Path.closePath()
bezier2Path.moveToPoint(CGPointMake(10.08, 12.66))
bezier2Path.addCurveToPoint(CGPointMake(14.58, 12.21), controlPoint1: CGPointMake(12.33, 14.38), controlPoint2: CGPointMake(14.58, 14.16))
bezier2Path.addCurveToPoint(CGPointMake(18.33, 11.08), controlPoint1: CGPointMake(14.58, 11.38), controlPoint2: CGPointMake(15.48, 11.08))
bezier2Path.addCurveToPoint(CGPointMake(22.08, 12.21), controlPoint1: CGPointMake(21.18, 11.08), controlPoint2: CGPointMake(22.08, 11.38))
bezier2Path.addCurveToPoint(CGPointMake(26.58, 12.66), controlPoint1: CGPointMake(22.08, 14.16), controlPoint2: CGPointMake(24.33, 14.38))
bezier2Path.addCurveToPoint(CGPointMake(32.21, 11.08), controlPoint1: CGPointMake(28.08, 11.61), controlPoint2: CGPointMake(29.88, 11.08))
bezier2Path.addCurveToPoint(CGPointMake(35.58, 13.33), controlPoint1: CGPointMake(35.43, 11.08), controlPoint2: CGPointMake(35.58, 11.16))
bezier2Path.addLineToPoint(CGPointMake(35.58, 15.58))
bezier2Path.addLineToPoint(CGPointMake(18.33, 15.58))
bezier2Path.addLineToPoint(CGPointMake(1.08, 15.58))
bezier2Path.addLineToPoint(CGPointMake(1.08, 13.33))
bezier2Path.addCurveToPoint(CGPointMake(4.46, 11.08), controlPoint1: CGPointMake(1.08, 11.16), controlPoint2: CGPointMake(1.23, 11.08))
bezier2Path.addCurveToPoint(CGPointMake(10.08, 12.66), controlPoint1: CGPointMake(6.78, 11.08), controlPoint2: CGPointMake(8.58, 11.61))
bezier2Path.closePath()
bezier2Path.moveToPoint(CGPointMake(11.21, 22.86))
bezier2Path.addCurveToPoint(CGPointMake(12.71, 28.71), controlPoint1: CGPointMake(11.21, 28.18), controlPoint2: CGPointMake(11.36, 28.71))
bezier2Path.addCurveToPoint(CGPointMake(14.43, 22.86), controlPoint1: CGPointMake(14.06, 28.71), controlPoint2: CGPointMake(14.21, 28.11))
bezier2Path.addCurveToPoint(CGPointMake(15.56, 17.08), controlPoint1: CGPointMake(14.58, 18.96), controlPoint2: CGPointMake(14.96, 17.08))
bezier2Path.addCurveToPoint(CGPointMake(16.23, 21.21), controlPoint1: CGPointMake(16.16, 17.08), controlPoint2: CGPointMake(16.38, 18.36))
bezier2Path.addCurveToPoint(CGPointMake(18.56, 28.93), controlPoint1: CGPointMake(15.86, 27.13), controlPoint2: CGPointMake(16.46, 29.23))
bezier2Path.addCurveToPoint(CGPointMake(20.21, 22.86), controlPoint1: CGPointMake(20.13, 28.71), controlPoint2: CGPointMake(20.21, 28.33))
bezier2Path.addCurveToPoint(CGPointMake(21.11, 17.08), controlPoint1: CGPointMake(20.21, 18.88), controlPoint2: CGPointMake(20.51, 17.08))
bezier2Path.addCurveToPoint(CGPointMake(22.23, 22.86), controlPoint1: CGPointMake(21.71, 17.08), controlPoint2: CGPointMake(22.08, 18.96))
bezier2Path.addCurveToPoint(CGPointMake(23.96, 28.71), controlPoint1: CGPointMake(22.46, 28.11), controlPoint2: CGPointMake(22.61, 28.71))
bezier2Path.addCurveToPoint(CGPointMake(25.46, 22.86), controlPoint1: CGPointMake(25.31, 28.71), controlPoint2: CGPointMake(25.46, 28.18))
bezier2Path.addLineToPoint(CGPointMake(25.46, 17.08))
bezier2Path.addLineToPoint(CGPointMake(29.43, 17.08))
bezier2Path.addCurveToPoint(CGPointMake(31.53, 24.58), controlPoint1: CGPointMake(33.93, 17.08), controlPoint2: CGPointMake(33.86, 16.78))
bezier2Path.addLineToPoint(CGPointMake(29.88, 30.21))
bezier2Path.addLineToPoint(CGPointMake(18.33, 30.21))
bezier2Path.addLineToPoint(CGPointMake(6.78, 30.21))
bezier2Path.addLineToPoint(CGPointMake(5.13, 24.58))
bezier2Path.addCurveToPoint(CGPointMake(7.31, 17.08), controlPoint1: CGPointMake(2.81, 16.78), controlPoint2: CGPointMake(2.73, 17.08))
bezier2Path.addLineToPoint(CGPointMake(11.21, 17.08))
bezier2Path.addLineToPoint(CGPointMake(11.21, 22.86))
bezier2Path.closePath()
bezier2Path.miterLimit = 4;
color0.setFill()
bezier2Path.fill()
return bezier2Path
}
// MARK: IBActions
@IBAction func postionValueChanged(sender: UISwitch) {
bubble.movesBottom = sender.on
}
@IBAction func animateIconValueChanged(sender: UISwitch) {
animateIcon = sender.on
}
@IBAction func snapInsideChanged(sender: UISwitch) {
bubble.snapsInside = sender.on
}
@IBAction func addPressed(sender: AnyObject) {
bubble.badgeCount++
}
@IBAction func removePressed(sender: AnyObject) {
bubble.badgeCount--
}
}
| mit |
luzefeng/iOS8-day-by-day | 31-touch-id/TouchyFeely/TouchyFeely/AppDelegate.swift | 44 | 921 | //
// Copyright 2014 Scott Logic
//
// 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
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
}
| apache-2.0 |
hejunbinlan/FileKit | FileKit/Core/FKDataType.swift | 5 | 1708 | //
// FKDataType.swift
// FileKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Nikolai Vazquez
//
// 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
/// A type that can be used to read and write `FKFile` instances.
public typealias FKDataType = protocol<FKReadable, FKWritable>
/// A type that can be used to read `FKFile` instances.
public protocol FKReadable {
/// Initializes `self` from a path.
init(contentsOfPath path: FKPath) throws
}
/// A type that can be used to write `FKFile` instances.
public protocol FKWritable {
/// Writes `self` to a path.
func writeToPath(path: FKPath) throws
}
| mit |
mac-cain13/game-of-life | Game of Life/Cell.swift | 1 | 319 | //
// Cell.swift
// Game of Life
//
// Created by Mathijs Kadijk on 15-03-15.
// Copyright (c) 2015 Mathijs Kadijk. All rights reserved.
//
enum Cell: Printable {
case Dead
case Alive
var description: String {
switch self {
case .Dead:
return " "
case .Alive:
return "O"
}
}
}
| mit |
robbdimitrov/pixelgram-ios | PixelGramTests/PixelGramTests.swift | 1 | 986 | //
// PixelGramTests.swift
// PixelGramTests
//
// Created by Robert Dimitrov on 10/24/17.
// Copyright © 2017 Robert Dimitrov. All rights reserved.
//
import XCTest
@testable import PixelGram
class PixelGramTests: 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.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
IntrepidPursuits/swift-wisdom | SwiftWisdom/Core/StandardLibrary/Set/Set+Utilities.swift | 1 | 925 | public extension Set {
func ip_toArray() -> [Element] {
return [Element](self)
}
@available (*, unavailable, message: "use allSatisfy(_:) instead")
func ip_passes(test: (Element) -> Bool) -> Bool {
for ob in self {
if test(ob) {
return true
}
}
return false
}
@available (*, unavailable, message: "use filter(_:) instead")
func ip_filter(_ include: (Element) -> Bool) -> Set<Element> {
var filtered = Set<Element>()
for ob in self {
if include(ob) {
filtered.insert(ob)
}
}
return filtered
}
}
// MARK: Operator Overloads
extension Set {
public static func += <T>(lhs: inout Set<T>, rhs: Set<T>) {
lhs = lhs.union(rhs)
}
public static func -= <T>(lhs: inout Set<T>, rhs: Set<T>) {
lhs = lhs.subtracting(rhs)
}
}
| mit |
SpectacularFigo/SwiftWB | SwiftWB/SwiftWB/Home/Model/FHStatues.swift | 1 | 1015 | //
// FHStatues.swift
// SwiftWB
//
// Created by Figo Han on 2017-02-16.
// Copyright © 2017 Figo Han. All rights reserved.
//
import UIKit
class FHStatues: NSObject {
// MARK:- properties
var created_at: String?
var idstr: String?
var text: String?
var source: String?
var user : FHUser?
var pic_urls : [[String : String]]?
var retweeted_status : FHStatues?
// MARK:- initializers and KVC
init(dict : [String : AnyObject]) {
super.init()
setValuesForKeys(dict)
if let user = dict["user"] as? [String : AnyObject]{
self.user = FHUser.init(dict: user)
}
if let retweeted_status = dict["retweeted_status"] as? [String : AnyObject] {
self.retweeted_status = FHStatues.init(dict: retweeted_status)
}
}
// for Undefined Key
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| apache-2.0 |
uias/Tabman | Sources/Tabman/Bar/BarIndicator/Types/TMBarIndicator+None.swift | 1 | 974 | //
// TMBarIndicator+None.swift
// Tabman
//
// Created by Merrick Sapsford on 28/09/2018.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
extension TMBarIndicator {
/// Indicator that is zero height and hidden.
///
/// Use this if you do not want a visible indicator in the bar.
public final class None: TMBarIndicator {
// MARK: Properties
public override var displayMode: TMBarIndicator.DisplayMode {
return .fill
}
// swiftlint:disable unused_setter_value
public override var isHidden: Bool {
get {
return super.isHidden
}
set {
super.isHidden = true
}
}
// MARK: Lifecycle
public override func layout(in view: UIView) {
super.layout(in: view)
super.isHidden = true
}
}
}
| mit |
Vostro162/VaporTelegram | Sources/App/Contact+Extensions.swift | 1 | 892 | //
// Contact+Extensions.swift
// VaporTelegram
//
// Created by Marius Hartig on 11.05.17.
//
//
import Foundation
import Vapor
// MARK: - JSON
extension Contact: JSONInitializable {
public init(json: JSON) throws {
guard
let phoneNumber = json["phone_number"]?.string,
let firstName = json["first_name"]?.string
else { throw VaporTelegramError.parsing }
self.phoneNumber = phoneNumber
self.firstName = firstName
/*
*
* Optionals
*
*/
if let lastName = json["last_name"]?.string {
self.lastName = lastName
} else {
self.lastName = nil
}
if let userId = json["user_id"]?.int {
self.userId = userId
} else {
self.userId = nil
}
}
}
| mit |
russelhampton05/MenMew | App Prototypes/Menu_Server_App_Prototype_001/Menu_Server_App_Prototype_001/RestaurantTableViewController.swift | 1 | 4421 | //
// RestaurantTableViewController.swift
// Menu_Server_App_Prototype_001
//
// Created by Jon Calanio on 10/3/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import UIKit
var currentTicket: Ticket?
class RestaurantTableViewController: UITableViewController, SWRevealViewControllerDelegate {
//IBOutlets
@IBOutlet weak var menuButton: UIBarButtonItem!
//Variables
var restaurantArray: [Restaurant] = []
var segueIndex: Int?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = false
tableView.sectionHeaderHeight = 70
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
navigationItem.hidesBackButton = true
menuButton.target = self.revealViewController()
self.revealViewController().delegate = self
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
//Load the assigned restaurants
loadRestaurants()
loadTheme()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
loadTheme()
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurantArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantCell", for: indexPath)
cell.textLabel!.text = restaurantArray[(indexPath as NSIndexPath).row].title
cell.detailTextLabel!.text = restaurantArray[(indexPath as NSIndexPath).row].location
cell.backgroundColor = currentTheme!.primary!
cell.textLabel!.textColor = currentTheme!.highlight!
cell.detailTextLabel!.textColor = currentTheme!.highlight!
//Interaction
let bgView = UIView()
bgView.backgroundColor = currentTheme!.highlight!
cell.selectedBackgroundView = bgView
cell.textLabel?.highlightedTextColor = currentTheme!.primary!
cell.detailTextLabel?.highlightedTextColor = currentTheme!.primary!
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
segueIndex = (indexPath as NSIndexPath).row
performSegue(withIdentifier: "TableListSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "TableListSegue" {
let tableVC = segue.destination as! RTableTableViewController
let backItem = UIBarButtonItem()
backItem.title = ""
navigationItem.backBarButtonItem = backItem
tableVC.restaurant = restaurantArray[segueIndex!]
}
}
func loadRestaurants() {
//For now, load all restaurants
var restaurantList: [String] = []
for item in currentServer!.restaurants! {
restaurantList.append(item)
}
RestaurantManager.GetRestaurant(ids: restaurantList) {
restaurants in
self.restaurantArray = restaurants
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
func loadTheme() {
//Background and Tint
self.view.backgroundColor = currentTheme!.primary!
self.view.tintColor = currentTheme!.highlight!
//Navigation
UINavigationBar.appearance().backgroundColor = currentTheme!.primary!
UINavigationBar.appearance().tintColor = currentTheme!.highlight!
self.navigationController?.navigationBar.barTintColor = currentTheme!.primary!
self.navigationController?.navigationBar.tintColor = currentTheme!.highlight!
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: currentTheme!.highlight!, NSFontAttributeName: UIFont.systemFont(ofSize: 20, weight: UIFontWeightLight)]
}
}
| mit |
dalbin/Eureka | Tests/HelperMethodTests.swift | 1 | 4253 | // HelperMethodTests.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2015 Xmartlabs ( 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 XCTest
@testable import Eureka
class HelperMethodTests: BaseEurekaTests {
func testRowByTag(){
// Tests rowByTag() method
let urlRow : URLRow? = fieldForm.rowByTag("UrlRow_f1")
XCTAssertNotNil(urlRow)
let phoneRow : PhoneRow? = fieldForm.rowByTag("phone")
XCTAssertNil(phoneRow)
}
func testRowSequenceMethods(){
// Tests the nextRowForRow() and the previousRowForRow() methods
let form = fieldForm + shortForm + dateForm
let row6 = form.nextRowForRow(form[0][5])
XCTAssertEqual(row6, form[0][6])
XCTAssertEqual(row6, form.rowByTag("IntRow_f1") as? IntRow)
let row_5_and_6: MutableSlice<Section> = form[0][5...6]
XCTAssertEqual(row_5_and_6[5], form[0][5])
XCTAssertEqual(row_5_and_6[6], form[0][6])
let row10n = form.nextRowForRow(form[0][8])
let rownil = form.nextRowForRow(form[2][7])
XCTAssertEqual(row10n, form[0][9])
XCTAssertNil(rownil)
let row10p = form.previousRowForRow(form[0][10])
let rowNilP = form.previousRowForRow(form[0][0])
XCTAssertEqual(row10n, row10p)
XCTAssertNil(rowNilP)
XCTAssertNotNil(form.nextRowForRow(form[1][1]))
XCTAssertEqual(form[1][1], form.previousRowForRow(form.nextRowForRow(form[1][1])!))
}
func testAllRowsMethod(){
// Tests the allRows() method
let form = fieldForm + shortForm + dateForm
XCTAssertEqual(form.rows.count, 21)
XCTAssertEqual(form.rows[12], shortForm[0][1])
XCTAssertEqual(form.rows[20], form.rowByTag("IntervalDateRow_d1") as? DateRow)
}
func testAllRowsWrappedByTagMethod(){
// Tests the allRows() method
let form = fieldForm + shortForm + dateForm
let rows = form.dictionaryValuesToEvaluatePredicate()
XCTAssertEqual(rows.count, 21)
}
func testDisabledRows(){
// Tests that a row set up as disabled can not become firstResponder
let checkRow = CheckRow("check"){ $0.disabled = true }
let switchRow = SwitchRow("switch"){ $0.disabled = true }
let segmentedRow = SegmentedRow<String>("segments"){ $0.disabled = true; $0.options = ["a", "b"] }
let intRow = IntRow("int"){ $0.disabled = true }
formVC.form +++ checkRow <<< switchRow <<< segmentedRow <<< intRow
checkRow.updateCell()
XCTAssertTrue(checkRow.cell.selectionStyle == .None)
switchRow.updateCell()
XCTAssertNotNil(switchRow.cell.switchControl)
XCTAssertFalse(switchRow.cell.switchControl!.enabled)
segmentedRow.updateCell()
XCTAssertFalse(segmentedRow.cell.segmentedControl.enabled)
intRow.updateCell()
XCTAssertFalse(intRow.cell.cellCanBecomeFirstResponder())
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/17808-no-stacktrace.swift | 11 | 223 | // 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 {
case
let h = a( [ {
func a {
{
}
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/19328-getselftypeforcontainer.swift | 11 | 213 | // 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 a<d : Range<c>
protocol c : b {
func b
| mit |
lstanii-magnet/ChatKitSample-iOS | ChatMessenger/Pods/ChatKit/ChatKit/source/Views/ContactsCell.swift | 1 | 1751 | /*
* Copyright (c) 2016 Magnet Systems, Inc.
* 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 UIKit
import MagnetMax
protocol ContactsCellDelegate : class {
func didSelectContactsCellAvatar(cell : ContactsCell)
}
public class ContactsCell: UITableViewCell {
//MARK: Public Properties
@IBOutlet public private(set) var avatar : UIImageView?
@IBOutlet public private(set)var userName : UILabel?
public internal(set) var user : MMUser?
//MARK: Internal properties
weak var delegate : ContactsCellDelegate?
//MARK: Actions
func didSelectAvatar() {
self.delegate?.didSelectContactsCellAvatar(self)
}
override public func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: "didSelectAvatar")
tap.cancelsTouchesInView = true
tap.delaysTouchesBegan = true
self.avatar?.userInteractionEnabled = true
self.avatar?.addGestureRecognizer(tap)
if let avatar = self.avatar {
avatar.layer.cornerRadius = avatar.frame.size.width / 2.0
avatar.clipsToBounds = true
}
}
}
| apache-2.0 |
austinzheng/swift-compiler-crashes | fixed/22154-swift-parser-parsestmtif.swift | 11 | 226 | // 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 end = Void{
let end = Void{
{
}
}
{
{
{
}
}
{
{
}
if
| mit |
raymondshadow/SwiftDemo | SwiftApp/Pods/Swiftz/Sources/Swiftz/Applicative.swift | 4 | 1525 | //
// Applicative.swift
// Swiftz
//
// Created by Maxwell Swadling on 15/06/2014.
// Copyright (c) 2014-2016 Maxwell Swadling. All rights reserved.
//
/// Applicative sits in the middle distance between a Functor and a Monad. An
/// Applicative Functor is a Functor equipped with a function (called point or
/// pure) that takes a value to an instance of a functor containing that value.
/// Applicative Functors provide the ability to operate on not just values, but
/// values in a functorial context such as Eithers, Lists, and Optionals without
/// needing to unwrap or map over their contents.
public protocol Applicative : Pointed, Functor {
/// Type of Functors containing morphisms from our objects to a target.
associatedtype FAB = K1<(A) -> B>
/// Applies the function encapsulated by the Functor to the value
/// encapsulated by the receiver.
func ap(_ f : FAB) -> FB
}
/// Additional functions to be implemented by those types conforming to the
/// Applicative protocol.
public protocol ApplicativeOps : Applicative {
associatedtype C
associatedtype FC = K1<C>
associatedtype D
associatedtype FD = K1<D>
/// Lift a function to a Functorial action.
static func liftA(_ f : @escaping (A) -> B) -> (Self) -> FB
/// Lift a binary function to a Functorial action.
static func liftA2(_ f : @escaping (A) -> (B) -> C) -> (Self) -> (FB) -> FC
/// Lift a ternary function to a Functorial action.
static func liftA3(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Self) -> (FB) -> (FC) -> FD
}
| apache-2.0 |
AliSoftware/Dip | Sources/Register.swift | 2 | 3421 | //
// Dip
//
// Copyright (c) 2015 Olivier Halligon <olivier@halligon.net>
//
// 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.
//
extension DependencyContainer {
/**
Registers definition for passed type.
If instance created by factory of definition, passed as a first parameter,
does not implement type passed in a `type` parameter,
container will throw `DipError.DefinitionNotFound` error when trying to resolve that type.
- parameters:
- definition: Definition to register
- type: Type to register definition for
- tag: Optional tag to associate definition with. Default is `nil`.
- returns: New definition registered for passed type.
*/
@discardableResult public func register<T, U, F>(_ definition: Definition<T, U>, type: F.Type, tag: DependencyTagConvertible? = nil) -> Definition<F, U> {
return _register(definition: definition, type: type, tag: tag)
}
/**
Register definiton in the container and associate it with an optional tag.
Will override already registered definition for the same type and factory, associated with the same tag.
- parameters:
- tag: The arbitrary tag to associate this definition with. Pass `nil` to associate with any tag. Default value is `nil`.
- definition: The definition to register in the container.
*/
public func register<T, U>(_ definition: Definition<T, U>, tag: DependencyTagConvertible? = nil) {
_register(definition: definition, tag: tag)
}
}
extension DependencyContainer {
func _register<T, U>(definition aDefinition: Definition<T, U>, tag: DependencyTagConvertible? = nil) {
precondition(!bootstrapped, "You can not modify container's definitions after it was bootstrapped.")
let definition = aDefinition
threadSafe {
let key = DefinitionKey(type: T.self, typeOfArguments: U.self, tag: tag?.dependencyTag)
if let _ = definitions[key] {
_remove(definitionForKey: key)
}
definition.container = self
definitions[key] = definition
resolvedInstances.singletons[key] = nil
resolvedInstances.weakSingletons[key] = nil
resolvedInstances.sharedSingletons[key] = nil
resolvedInstances.sharedWeakSingletons[key] = nil
if .eagerSingleton == definition.scope {
bootstrapQueue.append({ _ = try self.resolve(tag: tag) as T })
}
}
}
}
| mit |
open-telemetry/opentelemetry-swift | Examples/Logging Tracer/Logger.swift | 1 | 548 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
class Logger {
static let startTime = Date()
static func printHeader() {
print("TimeSinceStart | ThreadId | API")
}
static func log(_ s: String) {
let output = String(format: "%.9f | %@ | %@", timeSinceStart(), Thread.current.description, s)
print(output)
}
private static func timeSinceStart() -> Double {
let start = startTime
return Date().timeIntervalSince(start)
}
}
| apache-2.0 |
bricepollock/HTMLRenderingTableView | HTMLRenderingTableView/AppDelegate.swift | 1 | 2171 | //
// AppDelegate.swift
// HTMLRenderingTableView
//
// Created by Brice Pollock on 4/27/15.
// Copyright (c) 2015 Brice Pollock. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 |
RocketChat/Rocket.Chat.iOS | Pods/DifferenceKit/Sources/Extensions/UIKitExtension.swift | 1 | 8731 | #if os(iOS) || os(tvOS)
import UIKit
public extension UITableView {
/// Applies multiple animated updates in stages using `StagedChangeset`.
///
/// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`.
/// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it.
/// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages.
///
/// - Parameters:
/// - stagedChangeset: A staged set of changes.
/// - animation: An option to animate the updates.
/// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated
/// updates should be stopped and performed reloadData. Default is nil.
/// - setData: A closure that takes the collection as a parameter.
/// The collection should be set to data-source of UITableView.
func reload<C>(
using stagedChangeset: StagedChangeset<C>,
with animation: @autoclosure () -> RowAnimation,
interrupt: ((Changeset<C>) -> Bool)? = nil,
setData: (C) -> Void
) {
reload(
using: stagedChangeset,
deleteSectionsAnimation: animation(),
insertSectionsAnimation: animation(),
reloadSectionsAnimation: animation(),
deleteRowsAnimation: animation(),
insertRowsAnimation: animation(),
reloadRowsAnimation: animation(),
interrupt: interrupt,
setData: setData
)
}
/// Applies multiple animated updates in stages using `StagedChangeset`.
///
/// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`.
/// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it.
/// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages.
///
/// - Parameters:
/// - stagedChangeset: A staged set of changes.
/// - deleteSectionsAnimation: An option to animate the section deletion.
/// - insertSectionsAnimation: An option to animate the section insertion.
/// - reloadSectionsAnimation: An option to animate the section reload.
/// - deleteRowsAnimation: An option to animate the row deletion.
/// - insertRowsAnimation: An option to animate the row insertion.
/// - reloadRowsAnimation: An option to animate the row reload.
/// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated
/// updates should be stopped and performed reloadData. Default is nil.
/// - setData: A closure that takes the collection as a parameter.
/// The collection should be set to data-source of UITableView.
func reload<C>(
using stagedChangeset: StagedChangeset<C>,
deleteSectionsAnimation: @autoclosure () -> RowAnimation,
insertSectionsAnimation: @autoclosure () -> RowAnimation,
reloadSectionsAnimation: @autoclosure () -> RowAnimation,
deleteRowsAnimation: @autoclosure () -> RowAnimation,
insertRowsAnimation: @autoclosure () -> RowAnimation,
reloadRowsAnimation: @autoclosure () -> RowAnimation,
interrupt: ((Changeset<C>) -> Bool)? = nil,
setData: (C) -> Void
) {
if case .none = window, let data = stagedChangeset.last?.data {
setData(data)
return reloadData()
}
for changeset in stagedChangeset {
if let interrupt = interrupt, interrupt(changeset), let data = stagedChangeset.last?.data {
setData(data)
return reloadData()
}
_performBatchUpdates {
setData(changeset.data)
if !changeset.sectionDeleted.isEmpty {
deleteSections(IndexSet(changeset.sectionDeleted), with: deleteSectionsAnimation())
}
if !changeset.sectionInserted.isEmpty {
insertSections(IndexSet(changeset.sectionInserted), with: insertSectionsAnimation())
}
if !changeset.sectionUpdated.isEmpty {
reloadSections(IndexSet(changeset.sectionUpdated), with: reloadSectionsAnimation())
}
for (source, target) in changeset.sectionMoved {
moveSection(source, toSection: target)
}
if !changeset.elementDeleted.isEmpty {
deleteRows(at: changeset.elementDeleted.map { IndexPath(row: $0.element, section: $0.section) }, with: deleteRowsAnimation())
}
if !changeset.elementInserted.isEmpty {
insertRows(at: changeset.elementInserted.map { IndexPath(row: $0.element, section: $0.section) }, with: insertRowsAnimation())
}
if !changeset.elementUpdated.isEmpty {
reloadRows(at: changeset.elementUpdated.map { IndexPath(row: $0.element, section: $0.section) }, with: reloadRowsAnimation())
}
for (source, target) in changeset.elementMoved {
moveRow(at: IndexPath(row: source.element, section: source.section), to: IndexPath(row: target.element, section: target.section))
}
}
}
}
private func _performBatchUpdates(_ updates: () -> Void) {
if #available(iOS 11.0, tvOS 11.0, *) {
performBatchUpdates(updates)
}
else {
beginUpdates()
updates()
endUpdates()
}
}
}
public extension UICollectionView {
/// Applies multiple animated updates in stages using `StagedChangeset`.
///
/// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`.
/// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it.
/// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages.
///
/// - Parameters:
/// - stagedChangeset: A staged set of changes.
/// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated
/// updates should be stopped and performed reloadData. Default is nil.
/// - setData: A closure that takes the collection as a parameter.
/// The collection should be set to data-source of UICollectionView.
func reload<C>(
using stagedChangeset: StagedChangeset<C>,
interrupt: ((Changeset<C>) -> Bool)? = nil,
setData: (C) -> Void
) {
if case .none = window, let data = stagedChangeset.last?.data {
setData(data)
return reloadData()
}
for changeset in stagedChangeset {
if let interrupt = interrupt, interrupt(changeset), let data = stagedChangeset.last?.data {
setData(data)
return reloadData()
}
performBatchUpdates({
setData(changeset.data)
if !changeset.sectionDeleted.isEmpty {
deleteSections(IndexSet(changeset.sectionDeleted))
}
if !changeset.sectionInserted.isEmpty {
insertSections(IndexSet(changeset.sectionInserted))
}
if !changeset.sectionUpdated.isEmpty {
reloadSections(IndexSet(changeset.sectionUpdated))
}
for (source, target) in changeset.sectionMoved {
moveSection(source, toSection: target)
}
if !changeset.elementDeleted.isEmpty {
deleteItems(at: changeset.elementDeleted.map { IndexPath(item: $0.element, section: $0.section) })
}
if !changeset.elementInserted.isEmpty {
insertItems(at: changeset.elementInserted.map { IndexPath(item: $0.element, section: $0.section) })
}
if !changeset.elementUpdated.isEmpty {
reloadItems(at: changeset.elementUpdated.map { IndexPath(item: $0.element, section: $0.section) })
}
for (source, target) in changeset.elementMoved {
moveItem(at: IndexPath(item: source.element, section: source.section), to: IndexPath(item: target.element, section: target.section))
}
})
}
}
}
#endif
| mit |
luizlopezm/ios-Luis-Trucking | Pods/Eureka/Source/Rows/LabelRow.swift | 1 | 1013 | //
// LabelRow.swift
// Eureka
//
// Created by Martin Barreto on 2/23/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
// MARK: LabelCell
public class LabelCellOf<T: Equatable>: Cell<T>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
height = { BaseRow.estimatedRowHeight }
}
public override func setup() {
super.setup()
selectionStyle = .None
}
public override func update() {
super.update()
}
}
public typealias LabelCell = LabelCellOf<String>
// MARK: LabelRow
public class _LabelRow: Row<String, LabelCell> {
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// Simple row that can show title and value but is not editable by user.
public final class LabelRow: _LabelRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
} | mit |
aperritano/SimpleMQTTClient | TestClient/ViewController.swift | 1 | 520 | //
// ViewController.swift
// TestClient
//
// Created by Anthony Perritano on 4/21/16.
// Copyright © 2016 Gianluca Venturini. 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.
}
}
| mit |
everald/JetPack | Sources/UI/z_ImageView+PHAssetSource.swift | 1 | 3436 | // File name prefixed with z_ to avoid compiler crash related to type extensions, nested types and order of Swift source files.
// TODO
// - allow passing PHImageRequestOptions, copy it and set .synchronous to false
// - allow using a custom PHImageManager, e.g. PHCachingImageManager
import Photos
import UIKit
public extension ImageView {
public struct PHAssetSource: Source, Equatable {
public var asset: PHAsset
public init(asset: PHAsset) {
self.asset = asset
}
public func createSession() -> Session? {
return PHAssetSourceSession(source: self)
}
}
}
public func == (a: ImageView.PHAssetSource, b: ImageView.PHAssetSource) -> Bool {
return a.asset == b.asset
}
private final class PHAssetSourceSession: ImageView.Session {
fileprivate var lastRequestedContentMode: PHImageContentMode?
fileprivate var lastRequestedSize = CGSize()
fileprivate var listener: ImageView.SessionListener?
fileprivate var requestId: PHImageRequestID?
fileprivate let source: ImageView.PHAssetSource
fileprivate init(source: ImageView.PHAssetSource) {
self.source = source
}
fileprivate func imageViewDidChangeConfiguration(_ imageView: ImageView) {
startOrRestartRequestForImageView(imageView)
}
fileprivate func startOrRestartRequestForImageView(_ imageView: ImageView) {
let optimalSize = imageView.optimalImageSize.scaleBy(imageView.optimalImageScale)
var size = self.lastRequestedSize
size.width = max(size.width, optimalSize.width)
size.height = max(size.height, optimalSize.height)
let contentMode: PHImageContentMode
switch imageView.scaling {
case .fitInside, .none:
contentMode = .aspectFit
case .fitHorizontally, .fitHorizontallyIgnoringAspectRatio, .fitIgnoringAspectRatio, .fitOutside, .fitVertically, .fitVerticallyIgnoringAspectRatio:
contentMode = .aspectFill
}
guard contentMode != lastRequestedContentMode || size != lastRequestedSize else {
return
}
stopRequest()
startRequestWithSize(size, contentMode: contentMode)
}
fileprivate func startRequestWithSize(_ size: CGSize, contentMode: PHImageContentMode) {
precondition(self.requestId == nil)
self.lastRequestedContentMode = contentMode
self.lastRequestedSize = size
let manager = PHImageManager.default()
let options = PHImageRequestOptions()
options.deliveryMode = .opportunistic
options.isNetworkAccessAllowed = true
options.resizeMode = .exact
options.isSynchronous = false
options.version = .current
requestId = manager.requestImage(for: source.asset, targetSize: size, contentMode: contentMode, options: options) { image, _ in
guard let image = image else {
return
}
let imageSize = image.size.scaleBy(image.scale)
self.lastRequestedSize.width = max(self.lastRequestedSize.width, imageSize.width)
self.lastRequestedSize.height = max(self.lastRequestedSize.height, imageSize.height)
self.listener?.sessionDidRetrieveImage(image)
}
}
fileprivate func startRetrievingImageForImageView(_ imageView: ImageView, listener: ImageView.SessionListener) {
precondition(self.listener == nil)
self.listener = listener
self.startOrRestartRequestForImageView(imageView)
}
fileprivate func stopRetrievingImage() {
listener = nil
stopRequest()
}
fileprivate func stopRequest() {
guard let requestId = requestId else {
return
}
PHImageManager.default().cancelImageRequest(requestId)
self.requestId = nil
}
}
| mit |
margotFilleton/mealShake | mealShake/Theme.swift | 1 | 271 | //
// Theme.swift
// mealShake
//
// Created by Margot Filleton on 09/04/2017.
// Copyright © 2017 Margot Filleton. All rights reserved.
//
import Foundation
import UIKit
import DynamicColor
public class Theme {
static let mainColor = UIColor(hex: 0xf27575)
}
| mit |
stendahls/AsyncTask | Tests/ThrowableTask.swift | 1 | 3229 | //
// ThrowableTask.swift
// AsyncTest
//
// Created by Thomas Sempf on 2017-03-06.
// Copyright © 2017 Stendahls. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import AsyncTask
class ThrowableTaskTest: 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 testTaskThrows() {
enum TaskError: Error {
case notFound
}
let load = {(path: String) -> ThrowableTask<Data> in
ThrowableTask {
Thread.sleep(forTimeInterval: 0.05)
switch path {
case "profile.png":
return Data()
case "index.html":
return Data()
default:
throw TaskError.notFound
}
}
}
XCTAssertNotNil(try? load("profile.png").await())
XCTAssertNotNil(try? load("index.html").await())
XCTAssertNotNil(try? [load("profile.png"), load("index.html")].awaitAll())
XCTAssertThrowsError(try load("random.txt").await())
XCTAssertThrowsError(try [load("profile.png"), load("index.html"), load("random.txt")].awaitAll())
}
func testThatAwaitResultReturnsFailureAfterTimeout() {
let echo = ThrowableTask { () -> String in
Thread.sleep(forTimeInterval: 0.5)
return "Hello"
}
let result = echo.awaitResult(.background, timeout: 0.05)
if case .success = result {
XCTFail()
}
}
func testThatAwaitThrowsAfterTimeout() {
let echo = ThrowableTask { () -> String in
Thread.sleep(forTimeInterval: 0.5)
return "Hello"
}
XCTAssertThrowsError(try echo.await(.background, timeout: 0.05))
}
}
| mit |
codestergit/swift | test/IDE/comment_extensions.swift | 3 | 8737 | // RUN: %target-swift-ide-test -print-comments -source-filename %S/Inputs/comment_extensions.swift -comments-xml-schema %S/../../bindings/xml/comment-xml-schema.rng | %FileCheck %s
// Content is in separate file in ./Inputs due to the "requires" keyword getting
// recognized by lit.
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}} line="{{.*}}" column="{{.*}}"><Name>attention()</Name><USR>s:14swift_ide_test9attentionyyF</USR><Declaration>func attention()</Declaration><Discussion><Attention><Para>This function is so hip and exciting, it can’t be trusted.</Para></Attention></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>author()</Name><USR>s:14swift_ide_test6authoryyF</USR><Declaration>func author()</Declaration><Discussion><Author><Para>Stephen</Para></Author></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>authors()</Name><USR>s:14swift_ide_test7authorsyyF</USR><Declaration>func authors()</Declaration><Discussion><Authors><Para></Para><List-Bullet><Item><Para>Homer</Para></Item><Item><Para>Mark</Para></Item><Item><Para>J.</Para></Item></List-Bullet></Authors></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>bug()</Name><USR>s:14swift_ide_test3bugyyF</USR><Declaration>func bug()</Declaration><Discussion><Bug><Para>rdar://problem/8675309</Para></Bug></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>complexity()</Name><USR>s:14swift_ide_test10complexityyyF</USR><Declaration>func complexity()</Declaration><Discussion><Complexity><Para>O(n log2(n))</Para></Complexity></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>copyright()</Name><USR>s:14swift_ide_test9copyrightyyF</USR><Declaration>func copyright()</Declaration><Discussion><Copyright><Para>2015 Apple, Inc.</Para></Copyright></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>date()</Name><USR>s:14swift_ide_test4dateyyF</USR><Declaration>func date()</Declaration><Discussion><Date><Para>Thu Apr 23 22:38:09 PDT 2015</Para></Date></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>experiment()</Name><USR>s:14swift_ide_test10experimentyyF</USR><Declaration>func experiment()</Declaration><Discussion><Experiment><Para>Try some more. The strawberries taste like strawberries.</Para></Experiment></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Class file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>Invariant</Name><USR>s:14swift_ide_test9InvariantV</USR><Declaration>struct Invariant</Declaration><Discussion><Invariant><Para>x not nil</Para></Invariant></Discussion></Class>]
// CHECK: {{.*}}DocCommentAsXML=none
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>note()</Name><USR>s:14swift_ide_test4noteyyF</USR><Declaration>func note()</Declaration><Discussion><Note><Para>This function is very hip and exciting.</Para></Note></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>postcondition(_:)</Name><USR>s:14swift_ide_test13postconditionySizF</USR><Declaration>func postcondition(_ x: inout Int)</Declaration><Discussion><Postcondition><Para>x is unchanged</Para></Postcondition></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=none
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>precondition(_:)</Name><USR>s:14swift_ide_test12preconditionySiF</USR><Declaration>func precondition(_ x: Int)</Declaration><Discussion><Precondition><Para><codeVoice>x < 100</codeVoice></Para></Precondition></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=none
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>remark()</Name><USR>s:14swift_ide_test6remarkyyF</USR><Declaration>func remark()</Declaration><Discussion><Remark><Para>Always, no, never forget to check your references.</Para></Remark></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>remarks()</Name><USR>s:14swift_ide_test7remarksyyF</USR><Declaration>func remarks()</Declaration><Discussion><Remarks><Para></Para><List-Bullet><Item><Para>Never let a bear approach you.</Para></Item></List-Bullet></Remarks></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>requires()</Name><USR>s:14swift_ide_test8requiresyyF</USR><Declaration>func requires()</Declaration><Discussion><Requires><Para></Para><List-Bullet><Item><Para>explicit package name. Just kidding!</Para></Item></List-Bullet></Requires></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>see()</Name><USR>s:14swift_ide_test3seeyyF</USR><Declaration>func see()</Declaration><Discussion><See><Para>the pie (it’s very good).</Para></See></Discussion></Function>] CommentXMLValid
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>since()</Name><USR>s:14swift_ide_test5sinceyyF</USR><Declaration>func since()</Declaration><Discussion><Since><Para>1809</Para></Since></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>todo()</Name><USR>s:14swift_ide_test4todoyyF</USR><Declaration>func todo()</Declaration><Discussion><TODO><Para>be</Para></TODO><TODO><Para>or not to be</Para></TODO></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>version()</Name><USR>s:14swift_ide_test7versionyyF</USR><Declaration>func version()</Declaration><Discussion><Version><Para>Beta.</Para></Version></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>warning()</Name><USR>s:14swift_ide_test7warningyyF</USR><Declaration>func warning()</Declaration><Discussion><Warning><Para>Share the road.</Para></Warning></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>imageWithEmptyURLAndBogusTitle()</Name><USR>s:14swift_ide_test30imageWithEmptyURLAndBogusTitleyyF</USR><Declaration>func imageWithEmptyURLAndBogusTitle()</Declaration><Abstract><Para><rawHTML><![CDATA[<img src="" alt="/bogus/url/as/title"/>]]></rawHTML></Para></Abstract></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>imageTitleAndAlt()</Name><USR>s:14swift_ide_test16imageTitleAndAltyyF</USR><Declaration>func imageTitleAndAlt()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para><rawHTML><![CDATA[<img src="/swift.png" title="Image Title" alt="Image Alt"/>]]></rawHTML></Para></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>imageAlt()</Name><USR>s:14swift_ide_test8imageAltyyF</USR><Declaration>func imageAlt()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para><rawHTML><![CDATA[<img src="/swift.png" alt="Image Alt"/>]]></rawHTML></Para></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>imageTitle()</Name><USR>s:14swift_ide_test10imageTitleyyF</USR><Declaration>func imageTitle()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para><rawHTML><![CDATA[<img src="/swift.png" title="Image Title" alt="Image Alt"/>]]></rawHTML></Para></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>urlWithQueryString()</Name><USR>s:14swift_ide_test18urlWithQueryStringyyF</USR><Declaration>func urlWithQueryString()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para>Test <Link href="http://apple.com?a=1&b=1&c=abc">a link</Link></Para></Discussion></Function>]
// CHECK: {{.*}}DocCommentAsXML=[<Function file="{{.*}}" line="{{.*}}" column="{{.*}}"><Name>imageWithAmpersandsInTitleAndAlt()</Name><USR>s:14swift_ide_test32imageWithAmpersandsInTitleAndAltyyF</USR><Declaration>func imageWithAmpersandsInTitleAndAlt()</Declaration><Abstract><Para>Brief.</Para></Abstract><Discussion><Para><rawHTML><![CDATA[<img src="http://apple.com" title="&&&" alt="&&&"/>]]></rawHTML></Para></Discussion></Function>]
| apache-2.0 |
githubxiangdong/DouYuZB | DouYuZB/DouYuZB/Classes/Home/Controller/RecommendViewController.swift | 1 | 3510 | //
// RecommendViewController.swift
// DouYuZB
//
// Created by new on 2017/4/25.
// Copyright © 2017年 9-kylins. All rights reserved.
//
import UIKit
private let kAdViewH = kScreenW * 3/8 // 广告栏的高度
private let kGameH :CGFloat = 90 // 游戏推荐的高度
class RecommendViewController: BaseAnchorViewController {
// MARK:- 懒加载属性
fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel()
fileprivate lazy var adView : RecommendAdv = {
let adView = RecommendAdv.recommendAdv()
adView.frame = CGRect(x: 0, y: -(kAdViewH + kGameH), width: kScreenW, height: kAdViewH)
return adView
}()
fileprivate lazy var gameView : GameRecommendView = {
let gameView = GameRecommendView.gameRecommendView()
gameView.frame = CGRect(x: 0, y: -kGameH, width: kScreenW, height: kGameH)
return gameView
}()
}
// MARK:- 设置Ui界面
extension RecommendViewController {
override func setupUI() {
// 1,先调用super
super.setupUI()
// 2, 将adView添加到collectioView上
collectionView.addSubview(adView)
// 3, 将game添加到collectionView
collectionView.addSubview(gameView)
// 4, 设置collectionView的内边距
collectionView.contentInset = UIEdgeInsetsMake(kAdViewH + kGameH, 0, 0, 0)
}
}
// MARK:- 请求数据
extension RecommendViewController {
override func loadData() {
// 0, 给父类的viewModel赋值
baseVM = recommendVM
// 1, 请求推荐数据
recommendVM.requestData {
// 1, 展示推荐数据
self.collectionView.reloadData()
// 2, 将数据传给gameView
var groups = self.recommendVM.anchorGroups
// 2.1, 移除前两组数据
groups.removeFirst()
groups.removeFirst()
// 2.2, 添加个更多组的图标
let moreModel = AnchorGroupModel()
moreModel.tag_name = "更多"
groups.append(moreModel)
self.gameView.groupModels = groups
// 3, 请求数据完成
self.loadDataFinished()
}
// 2, 请求广告栏数据
recommendVM.requestAds {
self.adView.adsModels = self.recommendVM.adsModels
}
}
}
extension RecommendViewController : UICollectionViewDelegateFlowLayout {
// 重写父类的返回cell的方法
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 1 {
// 1, 取出niceCell
let niceCell = collectionView.dequeueReusableCell(withReuseIdentifier: kNiceCellID, for: indexPath) as! NiceCollectionViewCell
// 2, 设置数据
niceCell.model = recommendVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return niceCell
} else {
return super.collectionView(collectionView, cellForItemAt: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kNiceItemH)
}
return CGSize(width: kItemW, height: kItemH)
}
}
| mit |