repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
frankcjw/CJWUtilsS | CJWUtilsS/QPLib/UI/LGView.swift | 1 | 6484 | //
// LGView.swift
// CJWUtilsS
//
// Created by Frank on 21/03/2017.
// Copyright © 2017 cen. All rights reserved.
//
import UIKit
import MZTimerLabel
class LGView: UIView {
}
public class LGColumnsCell: QPTableViewCell {
public var columnView: QPColumnsView!
public override func setupViews(view: UIView) {
super.setupViews(view)
let count = numberOfColumn()
columnView = QPColumnsView(count: count)
view.addSubview(columnView)
columnView.custom { (label, index) in
label.textColor = UIColor.darkGrayColor()
}
columnView.hideLines()
}
public override func setupConstrains(view: UIView) {
super.setupConstrains(view)
columnView.equalConstrain()
columnView.heightConstrain("\(heightPredicate())")
}
public func heightPredicate() -> String {
return ">=44"
}
public func numberOfColumn() -> Int {
return 1
}
}
public class LGColumnsCell2: LGColumnsCell {
public override func numberOfColumn() -> Int {
return 2
}
}
public class LGColumnsCell3: LGColumnsCell {
public override func numberOfColumn() -> Int {
return 3
}
}
public class LGColumnsCell4: LGColumnsCell {
public override func numberOfColumn() -> Int {
return 4
}
}
public class LGColumnsCell5: LGColumnsCell {
public override func numberOfColumn() -> Int {
return 5
}
}
public class LGColumnsCell6: LGColumnsCell {
public override func numberOfColumn() -> Int {
return 6
}
}
/// 标题 大标题
public class LGColumnsTitleCell: QPTableViewCell {
public var columnView: QPColumnsView!
public override func setupViews(view: UIView) {
super.setupViews(view)
let count = numberOfColumn()
columnView = QPColumnsView(count: count)
view.addSubview(columnView)
}
public override func setupConstrains(view: UIView) {
super.setupConstrains(view)
columnView.equalConstrain()
columnView.heightConstrain(">=150")
}
public func numberOfColumn() -> Int {
return 1
}
public override func drawRect(rect: CGRect) {
super.drawRect(rect)
}
public func setTitle(title: String, subtitle: String, label: UILabel) {
label.text = "\(title)\n\n\(subtitle)"
let range = NSMakeRange(0, title.length())
label.setTextFont(UIFont.systemFontOfSize(40), atRange: range)
label.textColor = UIColor.whiteColor()
label.setTextColor(UIColor.mainColor(), atRange: range)
}
}
public class LGColumnsTitleCell2: LGColumnsTitleCell {
public override func numberOfColumn() -> Int {
return 2
}
}
public class LGColumnsTitleCell3: LGColumnsTitleCell {
public override func numberOfColumn() -> Int {
return 3
}
}
public class LGTimerLabel: UILabel {
public typealias LGTimerLabelBlock = () -> ()
public typealias LGTimerLabelCanBlock = () -> Bool
var block: LGTimerLabelBlock?
var startBlock: LGTimerLabelBlock?
var canStartBlock: LGTimerLabelCanBlock?
public func onTimesUp(block: LGTimerLabelBlock) {
self.block = block
}
public func canStart(block: LGTimerLabelCanBlock) {
self.canStartBlock = block
}
public func onStart(block: LGTimerLabelBlock) {
self.startBlock = block
}
var actoun: Selector?
var target: AnyObject?
public override func addTapGesture(target: AnyObject?, action: Selector) {
self.onStart {
target?.performSelector(action, withObject: nil)
// self.performSelector(action, withObject: target)
// action.
}
}
func startCounting(startDate: NSDate) {
userInteractionEnabled = false
self.timer = MZTimerLabel(label: self, andTimerType: MZTimerLabelTypeTimer)
self.timer.timeFormat = "重新获取(ss)"
let date = startDate.dateByAddingTimeInterval(60)
self.timer.setCountDownToDate(date)
self.timer.startWithEndingBlock { (time) in
self.text = "点击获取"
self.userInteractionEnabled = true
self.block?()
LGTimerUtils.sharedInstance.startDate = nil
}
}
func setupTimer() {
let date = NSDate()
if let startDate = LGTimerUtils.sharedInstance.startDate {
let min = startDate.minutesBeforeDate(date)
log.debug("min \(min) \(date) \(startDate)")
if min <= 1 {
let date = NSDate()
startCounting(startDate)
} else {
}
} else {
// startCounting()
}
}
var timer: MZTimerLabel!
func onTap() {
// if let block = canStartBlock {
//
// }else{
// }
var flag = true
if let block = canStartBlock {
flag = block()
}
if flag {
let startDate = NSDate()
LGTimerUtils.sharedInstance.startDate = startDate
startCounting(startDate)
startBlock?()
}
}
convenience init () {
self.init(frame: CGRect.zero)
setup(self)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup(self)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup(self)
}
override public func updateConstraints() {
super.updateConstraints()
cornorRadius(5)
}
func setup(view: UIView) {
// self.userInteractionEnabled = true
// let tap = UITapGestureRecognizer(target: self, action: #selector(LGTimerLabel.onTap))
// self.addGestureRecognizer(tap)
super.addTapGesture(self, action: #selector(LGTimerLabel.onTap))
// super.addTapGesture(self, action: <#T##Selector#>)
setupTimer()
self.backgroundColor = UIColor.mainColor()
self.textColor = UIColor.whiteColor()
self.fontNormal()
textAlignmentCenter()
self.text = "获取验证码"
}
public override func drawRect(rect: CGRect) {
super.drawRect(rect)
}
}
public class LGTimerUtils: NSObject {
var startDate: NSDate?
public class var sharedInstance: LGTimerUtils {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: LGTimerUtils? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = LGTimerUtils()
}
return Static.instance!
}
}
| mit | afac5894234bed8f2bdd5451d149d1c2 | 23.420455 | 97 | 0.627734 | 4.159355 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/ReadingListsCollectionViewCell.swift | 1 | 16718 | class ReadingListsCollectionViewCell: ArticleCollectionViewCell {
private var bottomSeparator = UIView()
private var topSeparator = UIView()
private var articleCountLabel = UILabel()
var articleCount: Int64 = 0
private let imageGrid = UIView()
private var gridImageViews: [UIImageView] = []
private var isDefault: Bool = false
private let defaultListTag = UILabel() // explains that the default list cannot be deleted
private var singlePixelDimension: CGFloat = 0.5
private var displayType: ReadingListsDisplayType = .readingListsTab
override var alertType: ReadingListAlertType? {
didSet {
guard let alertType = alertType else {
return
}
var alertLabelText: String? = nil
switch alertType {
case .listLimitExceeded:
alertLabelText = WMFLocalizedString("reading-lists-list-not-synced-limit-exceeded", value: "List not synced, limit exceeded", comment: "Text of the alert label informing the user that list couldn't be synced.")
case .entryLimitExceeded:
alertLabelText = WMFLocalizedString("reading-lists-articles-not-synced-limit-exceeded", value: "Some articles not synced, limit exceeded", comment: "Text of the alert label informing the user that some articles couldn't be synced.")
default:
break
}
alertLabel.text = alertLabelText
if !isAlertIconHidden {
alertIcon.image = UIImage(named: "error-icon")
}
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
singlePixelDimension = traitCollection.displayScale > 0 ? 1.0 / traitCollection.displayScale : 0.5
}
override func setup() {
imageView.layer.cornerRadius = 3
bottomSeparator.isOpaque = true
contentView.addSubview(bottomSeparator)
topSeparator.isOpaque = true
contentView.addSubview(topSeparator)
contentView.addSubview(articleCountLabel)
contentView.addSubview(defaultListTag)
let topRow = UIStackView(arrangedSubviews: [UIImageView(), UIImageView()])
topRow.axis = NSLayoutConstraint.Axis.horizontal
topRow.distribution = UIStackView.Distribution.fillEqually
let bottomRow = UIStackView(arrangedSubviews: [UIImageView(), UIImageView()])
bottomRow.axis = NSLayoutConstraint.Axis.horizontal
bottomRow.distribution = UIStackView.Distribution.fillEqually
gridImageViews = (topRow.arrangedSubviews + bottomRow.arrangedSubviews).compactMap { $0 as? UIImageView }
gridImageViews.forEach {
$0.accessibilityIgnoresInvertColors = true
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
let outermostStackView = UIStackView(arrangedSubviews: [topRow, bottomRow])
outermostStackView.axis = NSLayoutConstraint.Axis.vertical
outermostStackView.distribution = UIStackView.Distribution.fillEqually
imageGrid.addSubview(outermostStackView)
outermostStackView.frame = imageGrid.frame
outermostStackView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageGrid.layer.cornerRadius = 3
imageGrid.masksToBounds = true
contentView.addSubview(imageGrid)
super.setup()
}
open override func reset() {
super.reset()
bottomSeparator.isHidden = true
topSeparator.isHidden = true
titleTextStyle = .semiboldBody
updateFonts(with: traitCollection)
}
override func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
articleCountLabel.font = UIFont.wmf_font(.caption2, compatibleWithTraitCollection: traitCollection)
defaultListTag.font = UIFont.wmf_font(.italicCaption2, compatibleWithTraitCollection: traitCollection)
}
override func updateBackgroundColorOfLabels() {
super.updateBackgroundColorOfLabels()
articleCountLabel.backgroundColor = labelBackgroundColor
defaultListTag.backgroundColor = labelBackgroundColor
}
override open func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
let size = super.sizeThatFits(size, apply: apply)
let layoutMargins = calculatedLayoutMargins
var widthMinusMargins = size.width - layoutMargins.left - layoutMargins.right
let minHeight = imageViewDimension + layoutMargins.top + layoutMargins.bottom
let minHeightMinusMargins = minHeight - layoutMargins.top - layoutMargins.bottom
let labelsAdditionalSpacing: CGFloat = 20
if !isImageGridHidden || !isImageViewHidden {
widthMinusMargins = widthMinusMargins - spacing - imageViewDimension - labelsAdditionalSpacing
}
var x = layoutMargins.left
if isDeviceRTL {
x = size.width - x - widthMinusMargins
}
var origin = CGPoint(x: x, y: layoutMargins.top)
if displayType == .readingListsTab {
let articleCountLabelSize = articleCountLabel.intrinsicContentSize
var x = origin.x
if isDeviceRTL {
x = size.width - articleCountLabelSize.width - layoutMargins.left
}
let articleCountLabelFrame = articleCountLabel.wmf_preferredFrame(at: CGPoint(x: x, y: origin.y), maximumSize: articleCountLabelSize, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += articleCountLabelFrame.layoutHeight(with: spacing)
articleCountLabel.isHidden = false
} else {
articleCountLabel.isHidden = true
}
let labelHorizontalAlignment: HorizontalAlignment = isDeviceRTL ? .right : .left
if displayType == .addArticlesToReadingList {
if isDefault {
let titleLabelFrame = titleLabel.wmf_preferredFrame(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += titleLabelFrame.layoutHeight(with: 0)
let descriptionLabelFrame = descriptionLabel.wmf_preferredFrame(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += descriptionLabelFrame.layoutHeight(with: 0)
} else {
let titleLabelFrame = titleLabel.wmf_preferredFrame(at: CGPoint(x: origin.x, y: layoutMargins.top), maximumSize: CGSize(width: widthMinusMargins, height: UIView.noIntrinsicMetric), minimumSize: CGSize(width: UIView.noIntrinsicMetric, height: minHeightMinusMargins), horizontalAlignment: labelHorizontalAlignment, verticalAlignment: .center, apply: apply)
origin.y += titleLabelFrame.layoutHeight(with: 0)
}
} else if (descriptionLabel.wmf_hasText || !isImageGridHidden || !isImageViewHidden) {
let titleLabelFrame = titleLabel.wmf_preferredFrame(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += titleLabelFrame.layoutHeight(with: spacing)
let descriptionLabelFrame = descriptionLabel.wmf_preferredFrame(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += descriptionLabelFrame.layoutHeight(with: 0)
} else {
let titleLabelFrame = titleLabel.wmf_preferredFrame(at: origin, maximumSize: CGSize(width: widthMinusMargins, height: UIView.noIntrinsicMetric), minimumSize: CGSize(width: UIView.noIntrinsicMetric, height: minHeightMinusMargins), horizontalAlignment: labelHorizontalAlignment, verticalAlignment: .center, apply: apply)
origin.y += titleLabelFrame.layoutHeight(with: 0)
if !isAlertIconHidden || !isAlertLabelHidden {
origin.y += titleLabelFrame.layoutHeight(with: spacing) + spacing * 2
}
}
descriptionLabel.isHidden = !descriptionLabel.wmf_hasText
origin.y += layoutMargins.bottom
let height = max(origin.y, minHeight)
let separatorXPositon: CGFloat = 0
let separatorWidth = size.width
if (apply) {
if (!bottomSeparator.isHidden) {
bottomSeparator.frame = CGRect(x: separatorXPositon, y: height - singlePixelDimension, width: separatorWidth, height: singlePixelDimension)
}
if (!topSeparator.isHidden) {
topSeparator.frame = CGRect(x: separatorXPositon, y: 0, width: separatorWidth, height: singlePixelDimension)
}
}
if (apply) {
let imageViewY = floor(0.5*height - 0.5*imageViewDimension)
var x = layoutMargins.right
if !isDeviceRTL {
x = size.width - x - imageViewDimension
}
imageGrid.frame = CGRect(x: x, y: imageViewY, width: imageViewDimension, height: imageViewDimension)
imageGrid.isHidden = isImageGridHidden
}
if (apply && !isImageViewHidden) {
let imageViewY = floor(0.5*height - 0.5*imageViewDimension)
var x = layoutMargins.right
if !isDeviceRTL {
x = size.width - x - imageViewDimension
}
imageView.frame = CGRect(x: x, y: imageViewY, width: imageViewDimension, height: imageViewDimension)
}
let yAlignedWithImageBottom = imageGrid.frame.maxY - layoutMargins.bottom - (0.5 * spacing)
if !isAlertIconHidden {
var x = origin.x
if isDeviceRTL {
x = size.width - alertIconDimension - layoutMargins.right
}
alertIcon.frame = CGRect(x: x, y: yAlignedWithImageBottom, width: alertIconDimension, height: alertIconDimension)
origin.y += alertIcon.frame.layoutHeight(with: 0)
}
if !isAlertLabelHidden {
var xPosition = alertIcon.frame.maxX + spacing
var yPosition = alertIcon.frame.midY - 0.5 * alertIconDimension
var availableWidth = widthMinusMargins - alertIconDimension - spacing
if isDeviceRTL {
xPosition = alertIcon.frame.minX - availableWidth - spacing
}
if isAlertIconHidden {
xPosition = origin.x
yPosition = yAlignedWithImageBottom
availableWidth = widthMinusMargins
}
let alertLabelFrame = alertLabel.wmf_preferredFrame(at: CGPoint(x: xPosition, y: yPosition), maximumWidth: availableWidth, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += alertLabelFrame.layoutHeight(with: 0)
}
if displayType == .readingListsTab && isDefault {
let defaultListTagSize = defaultListTag.intrinsicContentSize
var x = origin.x
if isDeviceRTL {
x = size.width - defaultListTagSize.width - layoutMargins.right
}
var y = yAlignedWithImageBottom
if !isAlertIconHidden || !isAlertLabelHidden {
let alertMinY = isAlertIconHidden ? alertLabel.frame.minY : alertIcon.frame.minY
y = descriptionLabel.frame.maxY + ((alertMinY - descriptionLabel.frame.maxY) * 0.25)
}
_ = defaultListTag.wmf_preferredFrame(at: CGPoint(x: x, y: y), maximumSize: defaultListTagSize, alignedBy: articleSemanticContentAttribute, apply: apply)
defaultListTag.isHidden = false
} else {
defaultListTag.isHidden = true
}
return CGSize(width: size.width, height: height)
}
override func configureForCompactList(at index: Int) {
layoutMarginsAdditions.top = 5
layoutMarginsAdditions.bottom = 5
titleTextStyle = .subheadline
descriptionTextStyle = .footnote
updateFonts(with: traitCollection)
imageViewDimension = 40
}
private var isImageGridHidden: Bool = false {
didSet {
imageGrid.isHidden = isImageGridHidden
setNeedsLayout()
}
}
func configureAlert(for readingList: ReadingList, listLimit: Int, entryLimit: Int) {
guard let error = readingList.APIError else {
return
}
switch error {
case .listLimit:
isAlertLabelHidden = false
isAlertIconHidden = false
alertType = .listLimitExceeded(limit: listLimit)
case .entryLimit:
isAlertLabelHidden = false
isAlertIconHidden = false
alertType = .entryLimitExceeded(limit: entryLimit)
default:
isAlertLabelHidden = true
isAlertIconHidden = true
}
let isAddArticlesToReadingListDisplayType = displayType == .addArticlesToReadingList
isAlertIconHidden = isAddArticlesToReadingListDisplayType
isAlertLabelHidden = isAddArticlesToReadingListDisplayType
}
func configure(readingList: ReadingList, isDefault: Bool = false, index: Int, shouldShowSeparators: Bool = false, theme: Theme, for displayType: ReadingListsDisplayType, articleCount: Int64, lastFourArticlesWithLeadImages: [WMFArticle], layoutOnly: Bool) {
configure(with: readingList.name, description: readingList.readingListDescription, isDefault: isDefault, index: index, shouldShowSeparators: shouldShowSeparators, theme: theme, for: displayType, articleCount: articleCount, lastFourArticlesWithLeadImages: lastFourArticlesWithLeadImages, layoutOnly: layoutOnly)
}
func configure(with name: String?, description: String?, isDefault: Bool = false, index: Int, shouldShowSeparators: Bool = false, theme: Theme, for displayType: ReadingListsDisplayType, articleCount: Int64, lastFourArticlesWithLeadImages: [WMFArticle], layoutOnly: Bool) {
articleSemanticContentAttribute = .unspecified
imageViewDimension = 100
self.displayType = displayType
self.isDefault = isDefault
self.articleCount = articleCount
articleCountLabel.text = String.localizedStringWithFormat(CommonStrings.articleCountFormat, articleCount).uppercased()
defaultListTag.text = WMFLocalizedString("saved-default-reading-list-tag", value: "This list cannot be deleted", comment: "Tag on the default reading list cell explaining that the list cannot be deleted")
titleLabel.text = name
descriptionLabel.text = description
let imageWidthToRequest = imageView.frame.size.width < 300 ? traitCollection.wmf_nearbyThumbnailWidth : traitCollection.wmf_leadImageWidth
let imageURLs = lastFourArticlesWithLeadImages.compactMap { $0.imageURL(forWidth: imageWidthToRequest) }
isImageGridHidden = imageURLs.count != 4 // we need 4 images for the grid
isImageViewHidden = !(isImageGridHidden && imageURLs.count >= 1) // we need at least one image to display
if !layoutOnly && !isImageGridHidden {
let _ = zip(gridImageViews, imageURLs).compactMap { $0.wmf_setImage(with: $1, detectFaces: true, onGPU: true, failure: { (error) in }, success: { })}
}
if isImageGridHidden, let imageURL = imageURLs.first {
if !layoutOnly {
imageView.wmf_setImage(with: imageURL, detectFaces: true, onGPU: true, failure: { (error) in }, success: { })
}
} else {
isImageViewHidden = true
}
if displayType == .addArticlesToReadingList {
configureForCompactList(at: index)
}
if shouldShowSeparators {
topSeparator.isHidden = index > 0
bottomSeparator.isHidden = false
} else {
bottomSeparator.isHidden = true
}
apply(theme: theme)
extractLabel?.text = nil
setNeedsLayout()
}
public override func apply(theme: Theme) {
super.apply(theme: theme)
bottomSeparator.backgroundColor = theme.colors.border
topSeparator.backgroundColor = theme.colors.border
articleCountLabel.textColor = theme.colors.secondaryText
defaultListTag.textColor = theme.colors.secondaryText
}
}
| mit | 032e7fb368179d7a92b9b17c21b6261d | 46.902579 | 370 | 0.656478 | 5.42264 | false | false | false | false |
Miguel-Herrero/Swift | Pokedex/Pokedex/Pokemon.swift | 1 | 6909 | //
// Pokemon.swift
// Pokedex
//
// Created by Miguel Herrero on 16/12/16.
// Copyright © 2016 Miguel Herrero. All rights reserved.
//
import Foundation
import Alamofire
class Pokemon {
fileprivate var _name: String!
fileprivate var _pokedexId: Int!
fileprivate var _description: String!
fileprivate var _type: String!
fileprivate var _defense: String!
fileprivate var _height: String!
fileprivate var _weight: String!
fileprivate var _attack: String!
fileprivate var _nextEvolutionText: String!
fileprivate var _nextEvolutionName: String!
fileprivate var _nextEvolutionId: String!
fileprivate var _nextEvolutionLevel: String!
fileprivate var _pokemonURL: String!
var name: String {
return _name
}
var pokedexId: Int {
return _pokedexId
}
var description: String {
if _description == nil {
_description = ""
}
return _description
}
var type: String {
if _type == nil {
_type = ""
}
return _type
}
var defense: String {
if _defense == nil {
_defense = ""
}
return _defense
}
var height: String {
if _height == nil {
_height = ""
}
return _height
}
var weight: String {
if _weight == nil {
_weight = ""
}
return _weight
}
var attack: String {
if _attack == nil {
_attack = ""
}
return _attack
}
var nextEvolutionText: String {
if _nextEvolutionText == nil {
_nextEvolutionText = ""
}
return _nextEvolutionText
}
var nextEvolutionName: String {
if _nextEvolutionName == nil {
_nextEvolutionName = ""
}
return _nextEvolutionName
}
var nextEvolutionId: String {
if _nextEvolutionId == nil {
_nextEvolutionId = ""
}
return _nextEvolutionId
}
var nextEvolutionLevel: String {
if _nextEvolutionLevel == nil {
_nextEvolutionLevel = ""
}
return _nextEvolutionLevel
}
init(name: String, pokedexId: Int) {
self._name = name
self._pokedexId = pokedexId
self._pokemonURL = "\(URL_BASE)\(URL_POKEMON)\(self._pokedexId!)"
}
func downloadPokemonDetails(completed: @escaping DownloadComplete) {
Alamofire.request(self._pokemonURL).responseJSON { (response) in
if let dict = response.result.value as? Dictionary<String, AnyObject> {
if let weight = dict["weight"] as? String {
self._weight = weight
}
if let height = dict["height"] as? String {
self._height = height
}
if let attack = dict["attack"] as? Int {
self._attack = "\(attack)"
}
if let defense = dict["defense"] as? Int {
self._defense = "\(defense)"
}
if let typesArray = dict["types"] as? [Dictionary<String, String>] , typesArray.count > 0 {
if let name = typesArray[0]["name"] {
self._type = name.capitalized
}
if typesArray.count > 1 {
for x in 1..<typesArray.count {
if let name = typesArray[x]["name"] {
self._type! += "/\(name.capitalized)"
}
}
}
} else {
self._type = ""
}
if let descriptionsArray = dict["descriptions"] as? [Dictionary<String, String>], descriptionsArray.count > 0 {
if let url = descriptionsArray[0]["resource_uri"] {
let descriptionURL = "\(URL_BASE)\(url)"
Alamofire.request(descriptionURL).responseJSON(completionHandler: { (response) in
if let descriptionDict = response.result.value as? Dictionary<String, AnyObject> {
if let description = descriptionDict["description"] as? String {
let replacedDescription = description.replacingOccurrences(of: "POKMON", with: "Pokemon")
self._description = replacedDescription
}
}
completed()
})
}
} else {
self._description = ""
}
if let evolutionsArray = dict["evolutions"] as? [Dictionary<String, AnyObject>], evolutionsArray.count > 0 {
if let nextEvolution = evolutionsArray[0]["to"] as? String {
if nextEvolution.range(of: "mega") == nil {
self._nextEvolutionName = nextEvolution
if let uri = evolutionsArray[0]["resource_uri"] as? String {
let newString = uri.replacingOccurrences(of: "/api/v1/pokemon/", with: "")
let nextEvolutionId = newString.replacingOccurrences(of: "/", with: "")
self._nextEvolutionId = nextEvolutionId
if let nextEvolutionLevel = evolutionsArray[0]["level"] {
if let level = nextEvolutionLevel as? Int {
self._nextEvolutionLevel = "\(level)"
}
} else {
self._nextEvolutionLevel = ""
}
}
}
}
}
}
completed()
}
}
}
| gpl-3.0 | 79a91001eb29bc8b154b5e6173bf5915 | 29.034783 | 127 | 0.411118 | 5.960311 | false | false | false | false |
chrisjmendez/swift-exercises | Authentication/Parse/C - Custom Login/CustomLogin/auth/AppLogInViewController.swift | 1 | 2842 | //
// AppLogInViewController.swift
// CustomLogin
//
// Created by tommy trojan on 6/23/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
import UIKit
import Parse
class AppLogInViewController: PFLogInViewController {
var textFieldBackground:UIImageView?
func modifyLogin(){
//Changebackground of TextFields
let bgLogIn:UIImage = UIImage(named: "btn_email.png" )!
//Background
self.logInView?.backgroundColor = UIColor.whiteColor()
//Login Button
let loginBtn = UIImage(named: "btn_login.png")
self.logInView?.logInButton?.setBackgroundImage(loginBtn, forState: UIControlState.Normal)
let loginHighlightBtn = UIImage(named: "btn_login_highlight.png")
self.logInView?.logInButton?.setBackgroundImage(loginHighlightBtn, forState: UIControlState.Highlighted)
//Login Title
self.logInView?.logInButton?.setTitle("Custom Login", forState: UIControlState.Normal)
self.logInView?.logInButton?.titleLabel?.shadowOffset = CGSizeMake(0, 0)
//TextFields
self.logInView?.usernameField?.textColor = UIColor.orangeColor()
self.logInView?.usernameField?.placeholder = "My Custom E-mail"
self.logInView?.usernameField?.layer.shadowOpacity = 0
self.logInView?.passwordField?.textColor = UIColor.orangeColor()
self.logInView?.passwordField?.placeholder = "My Custom Password"
self.logInView?.passwordField?.layer.shadowOpacity = 0
//TextField background
let bgUserName = UIImage(named: "bg_email.png")
textFieldBackground = UIImageView(image: bgUserName)
self.logInView?.addSubview(textFieldBackground!)
self.logInView?.sendSubviewToBack(textFieldBackground!)
}
func positionTextFields(){
var screenHeight = UIScreen.mainScreen().bounds.size.height
var newSize:Int = (screenHeight <= 480) ? 615 : 270
textFieldBackground?.frame = CGRect(x: 0, y: newSize, width: 400, height: 48)
}
func modifySignup(){
self.logInView?.signUpButton?.setTitle("Custom Signup", forState: UIControlState.Normal)
self.logInView?.signUpButton?.titleLabel?.shadowOffset = CGSizeMake(0, 0)
}
func modifyLogo(){
let image:UIImage = UIImage(named: "logo_76x76.png")!
let logo:UIImageView = UIImageView(image: image)
logo.frame = CGRect(x: 0, y: 0, width: 76, height: 76)
self.logInView?.logo = logo
}
override func viewDidLoad() {
modifyLogin()
modifySignup()
modifyLogo()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//Position the BG of the text fields
// positionTextFields()
}
}
| mit | c84ea289ee90429a2d60202da576edc2 | 33.240964 | 112 | 0.657987 | 4.825127 | false | false | false | false |
tlax/GaussSquad | GaussSquad/View/LinearEquations/Project/Items/VLinearEquationsProjectCellNewPolynomial.swift | 1 | 725 | import UIKit
class VLinearEquationsProjectCellNewPolynomial:VLinearEquationsProjectCell
{
override init(frame:CGRect)
{
super.init(frame:frame)
let imageView:UIImageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
imageView.isUserInteractionEnabled = false
imageView.image = #imageLiteral(resourceName: "assetGenericColNew")
addSubview(imageView)
NSLayoutConstraint.equals(
view:imageView,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit | 10abb41c9fff0b0b1cfa591da39d2028 | 25.851852 | 75 | 0.656552 | 5.753968 | false | false | false | false |
Antondomashnev/Sourcery | Pods/SourceKittenFramework/Source/SourceKittenFramework/Structure.swift | 2 | 1651 | //
// Structure.swift
// SourceKitten
//
// Created by JP Simard on 2015-01-06.
// Copyright (c) 2015 SourceKitten. All rights reserved.
//
import Foundation
/// Represents the structural information in a Swift source file.
public struct Structure {
/// Structural information as an [String: SourceKitRepresentable].
public let dictionary: [String: SourceKitRepresentable]
/**
Create a Structure from a SourceKit `editor.open` response.
- parameter sourceKitResponse: SourceKit `editor.open` response.
*/
public init(sourceKitResponse: [String: SourceKitRepresentable]) {
var sourceKitResponse = sourceKitResponse
_ = sourceKitResponse.removeValue(forKey: SwiftDocKey.syntaxMap.rawValue)
dictionary = sourceKitResponse
}
/**
Initialize a Structure by passing in a File.
- parameter file: File to parse for structural information.
*/
public init(file: File) {
self.init(sourceKitResponse: Request.editorOpen(file: file).send())
}
}
// MARK: CustomStringConvertible
extension Structure: CustomStringConvertible {
/// A textual JSON representation of `Structure`.
public var description: String { return toJSON(toNSDictionary(dictionary)) }
}
// MARK: Equatable
extension Structure: Equatable {}
/**
Returns true if `lhs` Structure is equal to `rhs` Structure.
- parameter lhs: Structure to compare to `rhs`.
- parameter rhs: Structure to compare to `lhs`.
- returns: True if `lhs` Structure is equal to `rhs` Structure.
*/
public func == (lhs: Structure, rhs: Structure) -> Bool {
return lhs.dictionary.isEqualTo(rhs.dictionary)
}
| mit | a7d08c4e938c17988641d3f00782a797 | 27.465517 | 81 | 0.709267 | 4.474255 | false | false | false | false |
richardpiazza/LCARSDisplayKit | Sources/LCARSDisplayKitUI/UIImage+LCARSDisplayKit.swift | 1 | 2654 | #if (os(iOS) || os(tvOS))
import UIKit
public extension UIImage {
/// Creates a UIImage from a path, filled with the specified color
static func image(with path: CGMutablePath, fillColor color: UIColor, context: CGContext?) -> UIImage? {
var image: UIImage? = nil
guard context != nil else {
return image
}
context?.setLineWidth(0)
context?.setFillColor(color.cgColor)
context?.addPath(path)
context?.fillPath()
image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
/// Creates a UIImage from a path, stroked with the specified color
static func image(with path: CGMutablePath, strokeColor color: UIColor, strokeWidth: CGFloat, context: CGContext?) -> UIImage? {
var image: UIImage? = nil
guard context != nil else {
return image
}
context?.setLineWidth(strokeWidth)
context?.setStrokeColor(color.cgColor)
context?.addPath(path)
context?.strokePath()
image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
/// Creates a `UIImage` by filling the provided path.
static func image(with path: CGMutablePath, size: CGSize, color: UIColor, context: CGContext?) -> UIImage? {
var image: UIImage? = nil
if size.width == 0 || size.height == 0 {
return image
}
if context == nil {
return image
}
context?.setLineWidth(0)
context?.setFillColor(color.cgColor)
context?.addPath(path)
context?.fillPath()
image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
/// Creates a `UIImage` by filling the provided paths with the provided colors.
static func image(with subpaths: [CGMutablePath], colors: [UIColor], size: CGSize, context: CGContext?) -> UIImage? {
var image: UIImage? = nil
guard subpaths.count != 0, subpaths.count == colors.count else {
return image
}
guard size.width != 0 && size.height != 0 else {
return image
}
guard let ctx = context else {
return image
}
ctx.setLineWidth(0)
for i in 0..<subpaths.count {
ctx.setFillColor(colors[i].cgColor)
ctx.addPath(subpaths[i])
ctx.fillPath()
}
image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
}
#endif
| mit | aeb05ec04f5e48e726e61eb96cb10bc6 | 27.537634 | 132 | 0.569329 | 5.308 | false | false | false | false |
sdkshredder/SocialMe | SocialMe/SocialMe/SwagView.swift | 1 | 2541 | //
// SwagView.swift
// SocialMe
//
// Created by Matt Duhamel on 6/9/15.
// Copyright (c) 2015 new. All rights reserved.
//
import UIKit
import Parse
@IBDesignable
class SwagView : UIView {
@IBOutlet weak var button: UIButton!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var textField: UITextField! {
didSet {
textField.text = PFUser.currentUser()?.username!
}
}
@IBInspectable var borderWidth : CGFloat = 1
@IBInspectable var cornerRadius : CGFloat = 1
@IBInspectable var backgroundButtonColor : UIColor = UIColor.darkGrayColor()
@IBInspectable var cancelButtonColor : UIColor = UIColor.darkGrayColor()
@IBInspectable var saveButtonColor : UIColor = UIColor.darkGrayColor()
@IBInspectable var borderColor : UIColor = UIColor.darkGrayColor()
func setupUsername() {
}
override func awakeFromNib() {
cancelButton.layer.borderWidth = borderWidth
cancelButton.layer.borderColor = cancelButtonColor.CGColor
cancelButton.layer.cornerRadius = cornerRadius
cancelButton.setTitleColor(cancelButtonColor, forState: .Normal)
cancelButton.backgroundColor = backgroundButtonColor
button.backgroundColor = backgroundButtonColor
button.setTitleColor(borderColor, forState: .Normal)
button.layer.borderWidth = borderWidth
button.layer.borderColor = borderColor.CGColor
button.layer.cornerRadius = cornerRadius
layer.cornerRadius = cornerRadius
layer.borderColor = UIColor.lightGrayColor().CGColor
layer.borderWidth = 1
setupUsername()
}
@IBAction func editTouch(sender: UIButton) {
var title : String
var color : UIColor
if sender.titleForState(.Normal) == "Edit" {
title = "Save"
textField.enabled = true
color = saveButtonColor
} else {
title = "Edit"
color = borderColor
textField.enabled = false
}
UIView.animateWithDuration(0.2, animations: {
sender.setTitle(title, forState: .Normal)
// sender.layer.borderColor = color.CGColor
sender.setTitleColor(color, forState: .Normal)
})
}
@IBAction func cancelTouch(sender: UIButton) {
UIView.animateWithDuration(0.2, animations: {
self.removeFromSuperview()
})
}
}
| mit | 810e6805e8b579be5ecfa2f58931433c | 30.37037 | 80 | 0.636757 | 5.239175 | false | false | false | false |
BelledonneCommunications/linphone-iphone | Classes/Swift/Voip/Views/Fragments/LocalVideoView.swift | 1 | 2470 | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import Foundation
import SnapKit
import linphonesw
class LocalVideoView: UIView {
//Layout constants
let corner_radius = 15.0
let aspect_ratio = 4.0/3.0
let switch_camera_button_margins = 8.0
let switch_camera_button_size = 30
var width : CGFloat
var dragZone : UIView? {
didSet {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(drag))
isUserInteractionEnabled = true
addGestureRecognizer(panGesture)
}
}
let switchCamera = UIImageView(image: UIImage(named:"voip_change_camera")?.tinted(with:.white))
var callData: CallData? = nil {
didSet {
callData?.isRemotelyRecorded.readCurrentAndObserve(onChange: { (isRemotelyRecording) in
self.isHidden = !(isRemotelyRecording == true)
})
}
}
required init?(coder: NSCoder) {
width = 0.0
super.init(coder: coder)
}
init (width:CGFloat) {
self.width = width
super.init(frame: .zero)
layer.cornerRadius = corner_radius
clipsToBounds = true
addSubview(switchCamera)
switchCamera.alignParentTop(withMargin: switch_camera_button_margins).alignParentRight(withMargin: switch_camera_button_margins).square(switch_camera_button_size).done()
switchCamera.contentMode = .scaleAspectFit
contentMode = .scaleAspectFill
switchCamera.onClick {
Core.get().toggleCamera()
}
setSizeConstraint()
}
func setSizeConstraint() {
size(w: width, h: width*aspect_ratio).done()
}
@objc func drag(_ sender:UIPanGestureRecognizer){
dragZone?.bringSubviewToFront(self)
let translation = sender.translation(in: dragZone)
center = CGPoint(x: center.x + translation.x, y: center.y + translation.y)
sender.setTranslation(CGPoint.zero, in: dragZone)
}
}
| gpl-3.0 | eac9651ddd880b3a937c84b21fbe0209 | 27.068182 | 171 | 0.732389 | 3.686567 | false | false | false | false |
jmgrosen/homepit2 | HomePit2/DetailTableViewController.swift | 1 | 5446 | //
// DetailViewController.swift
// HomePit2
//
// Created by John Grosen on 7/7/14.
// Copyright (c) 2014 John Grosen. All rights reserved.
//
import UIKit
import HomeKit
/*
func findCharacteristic(service: HMService, name: String) -> HMCharacteristic? {
for cha in service.characteristics as HMCharacteristic[] {
if cha.characteristicType == name {
return cha
}
}
return nil
}
*/
protocol ServiceDelegate {
func characteristicValueDidChange(cha: HMCharacteristic)
func serviceNameDidChange()
}
class DetailTableViewController: UITableViewController, UISplitViewControllerDelegate, HMAccessoryDelegate {
var masterPopoverController: UIPopoverController? = nil
var lightbulbServices: HMService[] = []
var serviceViews: [HMService: ServiceDelegate] = [HMService: ServiceDelegate]()
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
if self.masterPopoverController != nil {
self.masterPopoverController!.dismissPopoverAnimated(true)
}
}
}
func configureView() {
// self.edgesForExtendedLayout = .None
// Update the user interface for the detail item.
if let acc: HMAccessory = self.detailItem as? HMAccessory {
let services = acc.services as [HMService]
self.lightbulbServices = services.filter({ s in s.serviceType == "public.hap.service.lightbulb" })
acc.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if self.lightbulbServices.count > 0 {
return 1
} else {
return 0
}
}
override func tableView(UITableView!, titleForHeaderInSection section: Int) -> String! {
switch (section) {
case 0:
return "Lightbulbs"
default:
return nil
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("I have \(self.lightbulbServices.count) lightbulbs ")
return self.lightbulbServices.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Lightbulb2", forIndexPath: indexPath) as UITableViewCell
println("cell = \(cell)")
println("making cell for row #\(indexPath.row)")
cell.backgroundView = UIView()
cell.backgroundColor = UIColor.clearColor()
let service = self.lightbulbServices[indexPath.row]
let view = LightbulbView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: cell.frame.size), service: service)
self.serviceViews[service] = view
cell.contentView.addSubview(view)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return false
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 230
}
// #pragma mark - accessory delegate
func accessory(_: HMAccessory!, didUpdateNameForService service: HMService!) {
println("didUpdateNameForService")
self.serviceViews[service]?.serviceNameDidChange()
}
func accessory(_: HMAccessory!, service: HMService!, didUpdateValueForCharacteristic cha: HMCharacteristic!) {
println("didUpdateValueForCharacteristic")
self.serviceViews[service]?.characteristicValueDidChange(cha)
}
// #pragma mark - Split view
func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) {
barButtonItem.title = "Accessories" // NSLocalizedString(@"Master", @"Master")
self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
self.masterPopoverController = popoverController
}
func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.masterPopoverController = nil
}
func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
| bsd-3-clause | 9d7564b15eda398b3d39edbb019ef8ef | 36.558621 | 238 | 0.688579 | 5.512146 | false | false | false | false |
mrommel/MiRoRecipeBook | MiRoRecipeBook/MiRoRecipeBook/Presentation/App/AppDelegate.swift | 1 | 3249 | //
// AppDelegate.swift
// com.bosch.ebike.mobile-app
//
// Created by Michael Rommel on 22.11.16.
// Copyright © 2016 MiRo Soft. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
static var shared: AppDelegate? = nil
var window: UIWindow?
var appDependecies: AppDependecies?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
AppDelegate.shared = self
self.appDependecies = AppDependecies.init(with: self.window!)
configureAppStyling()
// init core data
CoreDataManager.sharedInstance()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
}
extension AppDelegate {
}
private extension AppDelegate {
func configureAppStyling() {
styleNavigationBar()
styleBarButtons()
}
func styleNavigationBar() {
UINavigationBar.appearance().barTintColor = ColorPalette.themeColor
UINavigationBar.appearance().tintColor = ColorPalette.tintColor
UINavigationBar.appearance().titleTextAttributes = [
NSAttributedString.Key.font : FontPalette.navBarTitleFont(),
NSAttributedString.Key.foregroundColor : ColorPalette.navigationBarTitleColor
]
}
func styleBarButtons() {
let barButtonTextAttributes = [
NSAttributedString.Key.font : FontPalette.navBarButtonFont(),
NSAttributedString.Key.foregroundColor : ColorPalette.tintColor
]
UIBarButtonItem.appearance().setTitleTextAttributes(barButtonTextAttributes, for: .normal)
}
}
| gpl-3.0 | be0e8259adeb828263fb2ea408ebfffe | 39.6 | 285 | 0.720751 | 5.542662 | false | false | false | false |
apple/swift-nio-transport-services | Sources/NIOTransportServices/NIOTSChannelOptions.swift | 1 | 7673 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 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
//
//===----------------------------------------------------------------------===//
#if canImport(Network)
import NIOCore
#if swift(>=5.6)
@preconcurrency import Network
#else
import Network
#endif
/// Options that can be set explicitly and only on bootstraps provided by `NIOTransportServices`.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
public struct NIOTSChannelOptions {
/// See: ``Types/NIOTSWaitForActivityOption``.
public static let waitForActivity = NIOTSChannelOptions.Types.NIOTSWaitForActivityOption()
/// See: ``Types/NIOTSEnablePeerToPeerOption``.
public static let enablePeerToPeer = NIOTSChannelOptions.Types.NIOTSEnablePeerToPeerOption()
/// See: ``Types/NIOTSAllowLocalEndpointReuse``.
public static let allowLocalEndpointReuse = NIOTSChannelOptions.Types.NIOTSAllowLocalEndpointReuse()
/// See: ``Types/NIOTSCurrentPathOption``.
public static let currentPath = NIOTSChannelOptions.Types.NIOTSCurrentPathOption()
/// See: ``Types/NIOTSMetadataOption``
public static let metadata = { (definition: NWProtocolDefinition) -> NIOTSChannelOptions.Types.NIOTSMetadataOption in
.init(definition: definition)
}
/// See: ``Types/NIOTSEstablishmentReportOption``.
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public static let establishmentReport = NIOTSChannelOptions.Types.NIOTSEstablishmentReportOption()
/// See: ``Types/NIOTSDataTransferReportOption``.
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public static let dataTransferReport = NIOTSChannelOptions.Types.NIOTSDataTransferReportOption()
/// See: ``Types/NIOTSMultipathOption``
public static let multipathServiceType = NIOTSChannelOptions.Types.NIOTSMultipathOption()
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
extension NIOTSChannelOptions {
/// A namespace for ``NIOTSChannelOptions`` datastructures.
public enum Types {
/// ``NIOTSWaitForActivityOption`` controls whether the `Channel` should wait for connection changes
/// during the connection process if the connection attempt fails. If Network.framework believes that
/// a connection may succeed in future, it may transition into the `.waiting` state. By default, this option
/// is set to `true` and NIO allows this state transition, though it does count time in that state against
/// the timeout. If this option is set to `false`, transitioning into this state will be treated the same as
/// transitioning into the `failed` state, causing immediate connection failure.
///
/// This option is only valid with ``NIOTSConnectionBootstrap``.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
public struct NIOTSWaitForActivityOption: ChannelOption, Equatable {
public typealias Value = Bool
public init() {}
}
/// ``NIOTSEnablePeerToPeerOption`` controls whether the `Channel` will advertise services using peer-to-peer
/// connectivity. Setting this to true is the equivalent of setting `NWParameters.enablePeerToPeer` to
/// `true`. By default this option is set to `false`.
///
/// This option must be set on the bootstrap: setting it after the channel is initialized will have no effect.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
public struct NIOTSEnablePeerToPeerOption: ChannelOption, Equatable {
public typealias Value = Bool
public init() {}
}
/// ``NIOTSAllowLocalEndpointReuse`` controls whether the `Channel` can reuse a TCP address recently used.
/// Setting this to true is the equivalent of setting at least one of `REUSEADDR` and `REUSEPORT` to
/// `true`. By default this option is set to `false`.
///
/// This option must be set on the bootstrap: setting it after the channel is initialized will have no effect.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
public struct NIOTSAllowLocalEndpointReuse: ChannelOption, Equatable {
public typealias Value = Bool
public init() {}
}
/// ``NIOTSCurrentPathOption`` accesses the `NWConnection.currentPath` of the underlying connection.
///
/// This option is only valid with ``NIOTSConnectionBootstrap``.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
public struct NIOTSCurrentPathOption: ChannelOption, Equatable {
public typealias Value = NWPath
public init() {}
}
/// ``NIOTSMetadataOption`` accesses the metadata for a given `NWProtocol`.
///
/// This option is only valid with ``NIOTSConnectionBootstrap``.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
public struct NIOTSMetadataOption: ChannelOption, Equatable {
public typealias Value = NWProtocolMetadata
let definition: NWProtocolDefinition
public init(definition: NWProtocolDefinition) {
self.definition = definition
}
}
/// ``NIOTSEstablishmentReportOption`` accesses the `NWConnection.EstablishmentReport` of the underlying connection.
///
/// This option is only valid with ``NIOTSConnectionBootstrap``.
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct NIOTSEstablishmentReportOption: ChannelOption, Equatable {
public typealias Value = EventLoopFuture<NWConnection.EstablishmentReport?>
public init() {}
}
/// ``NIOTSDataTransferReportOption`` accesses the `NWConnection.DataTransferReport` of the underlying connection.
///
/// This option is only valid with ``NIOTSConnectionBootstrap``.
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public struct NIOTSDataTransferReportOption: ChannelOption, Equatable {
public typealias Value = NWConnection.PendingDataTransferReport
public init() {}
}
/// ``NIOTSMultipathOption`` sets the multipath behaviour for a given `NWConnection`
/// or `NWListener`.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
public struct NIOTSMultipathOption: ChannelOption, Equatable {
public typealias Value = NWParameters.MultipathServiceType
public init() {}
}
}
}
/// See: ``NIOTSChannelOptions/Types/NIOTSWaitForActivityOption``.
@available(*, deprecated, renamed: "NIOTSChannelOptions.Types.NIOTSWaitForActivityOption")
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
public typealias NIOTSWaitForActivityOption = NIOTSChannelOptions.Types.NIOTSWaitForActivityOption
/// See: ``NIOTSChannelOptions/Types/NIOTSEnablePeerToPeerOption``
@available(*, deprecated, renamed: "NIOTSChannelOptions.Types.NIOTSEnablePeerToPeerOption")
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
public typealias NIOTSEnablePeerToPeerOption = NIOTSChannelOptions.Types.NIOTSEnablePeerToPeerOption
#endif
| apache-2.0 | 677e88b879a0ec0fb84e039afbc7d71f | 45.50303 | 124 | 0.668578 | 4.313097 | false | false | false | false |
laszlokorte/reform-swift | ReformApplication/ReformApplication/StageViewModel.swift | 1 | 798 | //
// StageViewModel.swift
// ReformApplication
//
// Created by Laszlo Korte on 26.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
import ReformStage
import ReformTools
final class StageViewModel {
let stage : Stage
let stageUI : StageUI
let toolController : ToolController
let selection : FormSelection
let camera: Camera
let selectionChanger : FormSelectionChanger
init(stage: Stage, stageUI: StageUI, toolController : ToolController, selection: FormSelection, camera: Camera, selectionChanger: FormSelectionChanger) {
self.stage = stage
self.stageUI = stageUI
self.toolController = toolController
self.selection = selection
self.camera = camera
self.selectionChanger = selectionChanger
}
} | mit | 930e6111469e3b76cd02341dcf17eed0 | 27.5 | 157 | 0.711418 | 4.427778 | false | false | false | false |
twostraws/HackingWithSwift | Classic/project25/Project25/ViewController.swift | 1 | 5055 | //
// ViewController.swift
// Project25
//
// Created by TwoStraws on 19/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import MultipeerConnectivity
import UIKit
class ViewController: UICollectionViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, MCSessionDelegate, MCBrowserViewControllerDelegate {
var images = [UIImage]()
var peerID: MCPeerID!
var mcSession: MCSession!
var mcAdvertiserAssistant: MCAdvertiserAssistant!
override func viewDidLoad() {
super.viewDidLoad()
title = "Selfie Share"
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(showConnectionPrompt))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(importPicture))
peerID = MCPeerID(displayName: UIDevice.current.name)
mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
mcSession.delegate = self
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageView", for: indexPath)
if let imageView = cell.viewWithTag(1000) as? UIImageView {
imageView.image = images[indexPath.item]
}
return cell
}
@objc func importPicture() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
present(picker, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.editedImage] as? UIImage else { return }
dismiss(animated: true)
images.insert(image, at: 0)
collectionView?.reloadData()
// 1
if mcSession.connectedPeers.count > 0 {
// 2
if let imageData = image.pngData() {
// 3
do {
try mcSession.send(imageData, toPeers: mcSession.connectedPeers, with: .reliable)
} catch {
let ac = UIAlertController(title: "Send error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(ac, animated: true)
}
}
}
}
@objc func showConnectionPrompt() {
let ac = UIAlertController(title: "Connect to others", message: nil, preferredStyle: .actionSheet)
ac.addAction(UIAlertAction(title: "Host a session", style: .default, handler: startHosting))
ac.addAction(UIAlertAction(title: "Join a session", style: .default, handler: joinSession))
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(ac, animated: true)
}
func startHosting(action: UIAlertAction) {
mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "hws-project25", discoveryInfo: nil, session: mcSession)
mcAdvertiserAssistant.start()
}
func joinSession(action: UIAlertAction) {
let mcBrowser = MCBrowserViewController(serviceType: "hws-project25", session: mcSession)
mcBrowser.delegate = self
present(mcBrowser, animated: true)
}
func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
}
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
}
func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {
}
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
dismiss(animated: true)
}
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
dismiss(animated: true)
}
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
switch state {
case MCSessionState.connected:
print("Connected: \(peerID.displayName)")
case MCSessionState.connecting:
print("Connecting: \(peerID.displayName)")
case MCSessionState.notConnected:
print("Not Connected: \(peerID.displayName)")
}
}
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
if let image = UIImage(data: data) {
DispatchQueue.main.async { [unowned self] in
self.images.insert(image, at: 0)
self.collectionView?.reloadData()
}
}
}
func sendImage(img: UIImage) {
if mcSession.connectedPeers.count > 0 {
if let imageData = img.pngData() {
do {
try mcSession.send(imageData, toPeers: mcSession.connectedPeers, with: .reliable)
} catch let error as NSError {
let ac = UIAlertController(title: "Send error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
}
}
}
| unlicense | c1171ba94b076c13ee536fd74c274c1c | 32.25 | 167 | 0.747131 | 4.201164 | false | false | false | false |
tigclaw/days-of-swift | Project 23/ChangeDateAndTime/ChangeDateAndTime/SelectDateViewController.swift | 1 | 6067 | //
// SelectDateViewController.swift
// ChangeDateAndTime
//
// Created by Angela Lin on 1/13/17.
// Copyright © 2017 Angela Lin. All rights reserved.
//
import UIKit
class SelectDateViewController: UIViewController {
// MARK:- UI Variables
var datePicker: UIDatePicker = {
let picker = UIDatePicker()
picker.translatesAutoresizingMaskIntoConstraints = false
picker.datePickerMode = .date
picker.backgroundColor = UIColor.white
return picker
}()
var timePicker: UIDatePicker = {
let picker = UIDatePicker()
picker.translatesAutoresizingMaskIntoConstraints = false
picker.datePickerMode = .time
picker.backgroundColor = UIColor.white
return picker
}()
var todaysDateLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
label.text = "Today is: "
label.font = UIFont.boldSystemFont(ofSize: 12)
label.textColor = UIColor.gray
label.numberOfLines = 1
return label
}()
let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
//dateFormatter.dateFormat = "MMMM d, yyyy 'at' h:mm a"
//todaysDateFormatter.dateFormat = "MMMM d, yyyy"
dateFormatter.dateFormat = "MMMM d, yyyy 'at' h:mm a"
return dateFormatter
}()
var todaysDate: Date = Date()
var dateToDisplay: Date = Date()
// MARK:- ViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Set Date and Time"
view.backgroundColor = UIColor(red: 235/255, green: 235/255, blue: 235/255, alpha: 1.0)
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(clickCancel(sender:)))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(clickDone(sender:)))
// set up picker views
view.addSubview(todaysDateLabel)
view.addSubview(datePicker)
view.addSubview(timePicker)
setupPickerViews()
// add functions to picker view to detect when value changed
datePicker.addTarget(self, action: #selector(datePickerValueChanged(sender:)), for: .valueChanged)
timePicker.addTarget(self, action: #selector(timePickerValueChanged(sender:)), for: .valueChanged)
// set up todays date (always show today's date)
updateTodaysDateLabel()
// IF ALREADY SELECTED FROM PICKER BEFORE....
updatePickerDate()
}
// MARK:- Functions
func clickCancel(sender: UIBarButtonItem) {
print(">>Cancel")
dismiss(animated: true, completion: nil)
}
func clickDone(sender: UIBarButtonItem) {
print(">>Done")
// get the Date from the todaysDate that was passed over from 1st view controller
// guard let todaysDateValue = todaysDateLabel.text else {
// print("error")
// return
// }
//let previousDate = dateFormatter.date(from: todaysDateValue)
var combinedDate = Date()
// Read the date/time from the 2 UIDatePickers
let date = datePicker.date
let time = timePicker.date
// Get BOTH datepicker and timepicker INTO ONE DATE
let calendar = NSCalendar.current
let timeComponents = calendar.dateComponents([.hour, .minute], from: time)
var dateComponents = calendar.dateComponents([.month, .day, .year], from: date)
dateComponents.hour = timeComponents.hour
dateComponents.minute = timeComponents.minute
guard let fullDateFromComponents = calendar.date(from: dateComponents) else {
fatalError("ERROR: could not combine time and date")
}
combinedDate = fullDateFromComponents
if let parentVC = self.presentingViewController as? MainViewController {
print("PASSS selectedDate back to 1st view -> \(dateFormatter.string(from:datePicker.date))")
parentVC.todaysDate = combinedDate
}
// close the viewcontroller
dismiss(animated: true, completion: nil)
}
func setupPickerViews() {
todaysDateLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 70).isActive = true
todaysDateLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
todaysDateLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10).isActive = true
todaysDateLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -10).isActive = true
todaysDateLabel.heightAnchor.constraint(equalToConstant: 60).isActive = true
datePicker.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
datePicker.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
datePicker.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
datePicker.topAnchor.constraint(equalTo: todaysDateLabel.bottomAnchor, constant: 0).isActive = true
timePicker.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
timePicker.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
timePicker.topAnchor.constraint(equalTo: datePicker.bottomAnchor, constant: 20).isActive = true
}
func datePickerValueChanged(sender: UIDatePicker) {
print("changed DATE")
}
func timePickerValueChanged(sender: UIDatePicker) {
print("changed TIME")
}
func updateTodaysDateLabel() {
todaysDateLabel.text = "Today's date: \(dateFormatter.string(from: todaysDate))"
}
func updatePickerDate() {
datePicker.date = dateToDisplay
//timePicker.date =
}
}
| mit | 152c0b49b7f4a57ee197ff80ffe4f6b4 | 35.987805 | 144 | 0.650676 | 5.118987 | false | false | false | false |
Mazy-ma/XMCustomUIViewControllerTransitions_Swift | XMCustomUIViewControllerTransitions/XMCustomUIViewControllerTransitions/Classes/CardViewController/CardViewController.swift | 1 | 2436 | //
// CardViewController.swift
// XMCustomUIViewControllerTransitions
//
// Created by TwtMac on 17/1/22.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class CardViewController: UIViewController {
var pageIndex: Int = 0
var yachtCard: YachtCard?
/// 定义/初始化工具类
let flipPresentAnimationController = FlipPresentAnimationController()
let flipDismissAnimationController = FlipDismissAnimationController()
let swipeInteractionController = SwipeInteractionController()
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var descLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
cardView.layer.cornerRadius = 25
cardView.layer.masksToBounds = true
descLabel.text = yachtCard?.desc
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
cardView.addGestureRecognizer(tap)
}
@objc private func tapAction() {
let vc = RevealViewController()
vc.yachtCard = yachtCard
/// 设置模态跳转的代理方法
vc.transitioningDelegate = self
/// 设置需要手势的控制器
swipeInteractionController.wireToViewController(vc: vc)
present(vc, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension CardViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
flipPresentAnimationController.originFrame = cardView.frame
return flipPresentAnimationController
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
flipDismissAnimationController.destinationFrame = cardView.frame
return flipDismissAnimationController
}
func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return swipeInteractionController.interactionInProgress ? swipeInteractionController : nil
}
}
| apache-2.0 | e4e28a15045d2a3de6bb10527a03a24d | 32.928571 | 170 | 0.72 | 5.952381 | false | false | false | false |
viviancrs/fanboy | FanBoy/Source/View/Detail/Cell/DetailCell.swift | 1 | 1235 | //
// DetailCell.swift
// FanBoy
//
// Created by Vivian Cristhine da Rosa Soares on 16/07/17.
// Copyright © 2017 CI&T. All rights reserved.
//
import UIKit
class DetailCell: UITableViewCell {
// MARK: - Properties
static let kCellReuseIdentifier = "DetailCellReuseIdentifier"
// MARK: - Outlets
@IBOutlet private weak var nameLabel: UILabel!
@IBOutlet private weak var valueLabel: UILabel!
// MARK: - Public Functions
func fill(_ detail: Detail) {
nameLabel.text = detail.name
valueLabel.text = detail.value
switch detail.type {
case .standard:
accessoryType = .none
break
case .text:
accessoryType = .disclosureIndicator
break
case .linked(_):
accessoryType = .none
if detail.value.isEmpty {
let activityView = UIActivityIndicatorView.init(activityIndicatorStyle: .gray)
activityView.startAnimating()
accessoryView = activityView
valueLabel.text = LocalizableStringConstants.Loading.localize()
}
break
default:
break
}
}
}
| gpl-3.0 | 4dcd785109ea603204b3c7aaa9695640 | 25.255319 | 94 | 0.579417 | 5.228814 | false | false | false | false |
jsutdolph/FiniteStateMachine | updated/FSM.swift | 1 | 4010 | //
// FSM.swift
//
// You are free to copy and modify this code as you wish
// No warranty is made as to the suitability of this for any purpose
//
// A Generic Finite State Machine
//
// Important Feature: All states can be completely specified in a static array
//
import Foundation
/**
a state for a Finite State Machine
*/
class State<StateValue, TM, TC>
{
let id : StateValue
let transitions: [Transition<StateValue, TM, TC>]
/**
id a unique id for the state
transitions a set of transitions which can take the FSM to a different state
*/
init(_ id: StateValue, transitions: [Transition<StateValue, TM, TC>])
{
self.id = id
self.transitions = transitions
}
func findFirstTransition(client_model : TM, client_controller : TC) -> Int?
{
var index = 0
for transition in transitions
{
if (transition.condition(client_model)) // we return the _first_ transition with true condition - ignore others
{
return index
}
index+=1
}
return nil
}
}
/**
a transition between states
*/
class Transition<StateValue, TM, TC>
{
let condition : (TM) -> Bool
let action : (TC) -> Void
let toStateId : StateValue
/**
condition a condition for the transition (return true to make the transition)
action a function to perform on making the transition
toStateId the new state to arrive at after the transition
*/
init(_ condition: @escaping (TM) -> Bool, action: @escaping (TC) -> Void, toStateId: StateValue)
{
self.condition = condition
self.action = action
self.toStateId = toStateId
}
}
/**
A Finite State Machine
*/
class FSM<StateValue : Hashable, TM, TC>
{
let logging = true
let states : [StateValue : State<StateValue, TM, TC>]
var currentState : State<StateValue, TM, TC>
func log(_ items: Any...)
{
if logging
{
print(items)
}
}
init(states : [State<StateValue, TM, TC>], initialStateId : StateValue)
{
var statesMap = [StateValue : State<StateValue, TM, TC>]()
for state in states {
statesMap[state.id] = state
}
self.states = statesMap
self.currentState = statesMap[initialStateId]!
assert(check())
log(states.count, " states in FSM")
}
/** (for debug) check that all transitions specify valid end states in states list
*/
func check() -> Bool
{
for state in states.values
{
for transition in state.transitions
{
if let _ = states[transition.toStateId] {
// nop
}
else {
return false // transition specifies state not in states list
}
}
}
return true
}
/** make at most one state transition and return true if a transition was made
*/
func cycleOnce(client_model : TM, client_controller : TC) -> Bool
{
if let transitionIndex = currentState.findFirstTransition(client_model : client_model, client_controller : client_controller) { // find a transition with true condition
let transition = currentState.transitions[transitionIndex]
transition.action(client_controller) // perform its action
let newState = states[transition.toStateId]! // move to new state - run-time error if state does not exist
if newState.id != currentState.id
{
log(" transition ", transitionIndex, " change from ", String(describing:currentState.id), " to ", String(describing:newState.id))
currentState = newState // change state
return true
}
}
return false
}
/** cycle until there is no state change, with the given maximum permitted number of cycles
return true if success, false if it stopped because maxCycles reached
*/
func cycleUntilStable(client_model : TM, client_controller : TC, maxCycles : Int) -> Bool
{
var traversedStates : Set = [currentState.id]
for cycles in 1...maxCycles
{
let changedState = cycleOnce(client_model: client_model, client_controller : client_controller)
if (!changedState)
{
if cycles > 2
{
log("executed ", cycles-1, " fsm transitions")
}
return true // stable
}
else
{
traversedStates.insert(currentState.id)
}
}
return false
}
}
| mit | 855f0e52d99bc41ed45d7c6be3b84d94 | 24.220126 | 170 | 0.686284 | 3.493031 | false | false | false | false |
oisdk/SwiftSequence | Sources/Categorise.swift | 1 | 5230 | // MARK: - Eager
// MARK: Categorise
private extension Dictionary {
subscript(key: Key, or or: Value) -> Value {
get { return self[key] ?? or }
set { self[key] = newValue }
}
}
public extension SequenceType {
/**
Categorises elements of `self` into a dictionary, with the keys
given by `keyFunc`
```swift
struct Person : CustomStringConvertible {
let name: String
let age : Int
init(_ name: String, _ age: Int) {
self.name = name
self.age = age
}
var description: String { return name }
}
let people = [
Person("Jo", 20),
Person("An", 20),
Person("Cthulu", 4000)
]
people.categorise { p in p.age }
//[20: [Jo, An], 4000: [Cthulu]]
```
*/
@warn_unused_result
func categorise<U : Hashable>(@noescape keyFunc: Generator.Element throws -> U)
rethrows -> [U:[Generator.Element]] {
var dict: [U:[Generator.Element]] = [:]
for el in self { dict[try keyFunc(el), or: []].append(el) }
return dict
}
}
public extension SequenceType where Generator.Element : Hashable {
// MARK: Frequencies
/**
Returns a dictionary where the keys are the elements of self, and
the values are their respective frequencies
```swift
[0, 3, 0, 1, 1, 3, 2, 3, 1, 0].freqs()
// [2: 1, 0: 3, 3: 3, 1: 3]
```
*/
@warn_unused_result
func freqs() -> [Generator.Element:Int] {
var freqs: [Generator.Element:Int] = [:]
for el in self { freqs[el, or: 0] += 1 }
return freqs
}
// MARK: Uniques
/**
Returns an array of the elements of `self`, in order, with
duplicates removed
```swift
[3, 1, 2, 3, 2, 1, 1, 2, 3, 3].uniques()
// [3, 1, 2]
```
*/
@warn_unused_result
public func uniques() -> [Generator.Element] {
var prevs: Set<Generator.Element> = []
var uniqs: [Generator.Element] = []
for el in self where !prevs.contains(el) {
prevs.insert(el)
uniqs.append(el)
}
return uniqs
}
/// Returns the element which occurs most frequently in `self`
@warn_unused_result
public func mostFrequent() -> Generator.Element? {
var freqs: [Generator.Element:Int] = [:]
var be: Generator.Element? = nil
var bc = 0
for el in self {
let nc = freqs[el, or: 0] + 1
freqs[el] = nc
if nc > bc { (be,bc) = (el,nc) }
}
return be
}
}
// MARK: - Lazy
// MARK: Uniques
/// :nodoc:
public struct UniquesGen<G : GeneratorType where G.Element : Hashable> : GeneratorType {
private var prevs: Set<G.Element>
private var g: G
/// :nodoc:
public mutating func next() -> G.Element? {
while let next = g.next() {
if !prevs.contains(next) {
prevs.insert(next)
return next
}
}
return nil
}
}
/// :nodoc:
public struct UniquesSeq<
S : SequenceType where
S.Generator.Element : Hashable
> : LazySequenceType {
private let seq: S
/// :nodoc:
public func generate() -> UniquesGen<S.Generator> {
return UniquesGen(prevs: [], g: seq.generate())
}
}
public extension LazySequenceType where Generator.Element : Hashable {
/// returns a `LazySequence` of the elements of `self`, in order, with
/// duplicates removed
@warn_unused_result
func uniques() -> UniquesSeq<Self> {
return UniquesSeq(seq: self)
}
}
// MARK: Grouping
/// :nodoc:
public struct GroupByGen<G : GeneratorType> : GeneratorType {
private var genr: G
private var last: G.Element?
private let isEq: (G.Element, G.Element) -> Bool
/// :nodoc:
mutating public func next() -> [G.Element]? {
guard let head = last else { return nil }
var group = [head]
last = nil
while let next = genr.next() {
guard isEq(group.last!, next) else {
last = next
return group
}
group.append(next)
}
return group
}
private init(g : G, isEquivalent: (G.Element, G.Element) -> Bool) {
genr = g
last = genr.next()
isEq = isEquivalent
}
}
/// :nodoc:
public struct GroupBySeq<S : SequenceType> : LazySequenceType {
private let seq: S
private let isEquivalent: (S.Generator.Element, S.Generator.Element) -> Bool
/// :nodoc:
public func generate() -> GroupByGen<S.Generator> {
return GroupByGen(g: seq.generate(), isEquivalent: isEquivalent)
}
}
public extension LazySequenceType where Generator.Element : Equatable {
/// Returns a lazy sequence of self, chunked into arrays of adjacent equal values
/// ```swift
/// [1, 2, 2, 3, 1, 1, 3, 4, 2].lazy.group()
///
/// [1], [2, 2], [3], [1, 1], [3], [4], [2]
/// ```
@warn_unused_result
func group() -> GroupBySeq<Self> {
return GroupBySeq(seq: self, isEquivalent: ==)
}
}
public extension LazySequenceType {
/// Returns a lazy sequence of self, chunked into arrays of adjacent equal values
/// - Parameter isEquivalent: a function that returns true if its two parameters are equal
/// ```swift
/// [1, 3, 5, 20, 22, 18, 6, 7].lazy.groupBy { (a,b) in abs(a - b) < 5 }
///
/// [1, 3, 5], [20, 22, 18], [6, 7]
/// ```
@warn_unused_result
func group(isEquivalent: (Generator.Element, Generator.Element) -> Bool)
-> GroupBySeq<Self> {
return GroupBySeq(seq: self, isEquivalent: isEquivalent)
}
}
| mit | 101c4847b5cbf431982aea4dd280a97e | 23.553991 | 92 | 0.606119 | 3.429508 | false | false | false | false |
lourenco-marinho/ActionButton | Source/ActionButton.swift | 1 | 10826 | // ActionButton.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 ActionButton
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public typealias ActionButtonAction = (ActionButton) -> Void
open class ActionButton: NSObject {
/// The action the button should perform when tapped
open var action: ActionButtonAction?
/// The button's background color : set default color and selected color
open var backgroundColor: UIColor = UIColor(red: 238.0/255.0, green: 130.0/255.0, blue: 34.0/255.0, alpha:1.0) {
willSet {
floatButton.backgroundColor = newValue
backgroundColorSelected = newValue
}
}
/// The button's background color : set default color
open var backgroundColorSelected: UIColor = UIColor(red: 238.0/255.0, green: 130.0/255.0, blue: 34.0/255.0, alpha:1.0)
/// Indicates if the buttons is active (showing its items)
fileprivate(set) open var active: Bool = false
/// An array of items that the button will present
internal var items: [ActionButtonItem]? {
willSet {
for abi in self.items! {
abi.view.removeFromSuperview()
}
}
didSet {
placeButtonItems()
showActive(true)
}
}
/// The button that will be presented to the user
fileprivate var floatButton: UIButton!
/// View that will hold the placement of the button's actions
fileprivate var contentView: UIView!
/// View where the *floatButton* will be displayed
fileprivate var parentView: UIView!
/// Blur effect that will be presented when the button is active
fileprivate var blurVisualEffect: UIVisualEffectView!
// Distance between each item action
fileprivate let itemOffset = -55
/// the float button's radius
fileprivate let floatButtonRadius = 50
public init(attachedToView view: UIView, items: [ActionButtonItem]?) {
super.init()
self.parentView = view
self.items = items
let bounds = self.parentView.bounds
self.floatButton = UIButton(type: .custom)
self.floatButton.layer.cornerRadius = CGFloat(floatButtonRadius / 2)
self.floatButton.layer.shadowOpacity = 1
self.floatButton.layer.shadowRadius = 2
self.floatButton.layer.shadowOffset = CGSize(width: 1, height: 1)
self.floatButton.layer.shadowColor = UIColor.gray.cgColor
self.floatButton.setTitle("+", for: UIControlState())
self.floatButton.setImage(nil, for: UIControlState())
self.floatButton.backgroundColor = self.backgroundColor
self.floatButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 35)
self.floatButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
self.floatButton.isUserInteractionEnabled = true
self.floatButton.translatesAutoresizingMaskIntoConstraints = false
self.floatButton.addTarget(self, action: #selector(ActionButton.buttonTapped(_:)), for: .touchUpInside)
self.floatButton.addTarget(self, action: #selector(ActionButton.buttonTouchDown(_:)), for: .touchDown)
self.parentView.addSubview(self.floatButton)
self.contentView = UIView(frame: bounds)
self.blurVisualEffect = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
self.blurVisualEffect.frame = self.contentView.frame
self.contentView.addSubview(self.blurVisualEffect)
let tap = UITapGestureRecognizer(target: self, action: #selector(ActionButton.backgroundTapped(_:)))
self.contentView.addGestureRecognizer(tap)
self.installConstraints()
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Set Methods
open func setTitle(_ title: String?, forState state: UIControlState) {
floatButton.setImage(nil, for: state)
floatButton.setTitle(title, for: state)
floatButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
}
open func setImage(_ image: UIImage?, forState state: UIControlState) {
setTitle(nil, forState: state)
floatButton.setImage(image, for: state)
floatButton.adjustsImageWhenHighlighted = false
floatButton.contentEdgeInsets = UIEdgeInsets.zero
}
//MARK: - Auto Layout Methods
/**
Install all the necessary constraints for the button. By the default the button will be placed at 15pts from the bottom and the 15pts from the right of its *parentView*
*/
fileprivate func installConstraints() {
let views: [String: UIView] = ["floatButton":self.floatButton, "parentView":self.parentView]
let width = NSLayoutConstraint.constraints(withVisualFormat: "H:[floatButton(\(floatButtonRadius))]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views)
let height = NSLayoutConstraint.constraints(withVisualFormat: "V:[floatButton(\(floatButtonRadius))]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views)
self.floatButton.addConstraints(width)
self.floatButton.addConstraints(height)
let trailingSpacing = NSLayoutConstraint.constraints(withVisualFormat: "V:[floatButton]-15-|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views)
let bottomSpacing = NSLayoutConstraint.constraints(withVisualFormat: "H:[floatButton]-15-|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views)
self.parentView.addConstraints(trailingSpacing)
self.parentView.addConstraints(bottomSpacing)
}
//MARK: - Button Actions Methods
func buttonTapped(_ sender: UIControl) {
animatePressingWithScale(1.0)
if let unwrappedAction = self.action {
unwrappedAction(self)
}
}
func buttonTouchDown(_ sender: UIButton) {
animatePressingWithScale(0.9)
}
//MARK: - Gesture Recognizer Methods
func backgroundTapped(_ gesture: UIGestureRecognizer) {
if self.active {
self.toggle()
}
}
//MARK: - Custom Methods
/**
Presents or hides all the ActionButton's actions
*/
open func toggleMenu() {
self.placeButtonItems()
self.toggle()
}
//MARK: - Action Button Items Placement
/**
Defines the position of all the ActionButton's actions
*/
fileprivate func placeButtonItems() {
if let optionalItems = self.items {
for item in optionalItems {
item.view.center = CGPoint(x: self.floatButton.center.x - 83, y: self.floatButton.center.y)
item.view.removeFromSuperview()
self.contentView.addSubview(item.view)
}
}
}
//MARK - Float Menu Methods
/**
Presents or hides all the ActionButton's actions and changes the *active* state
*/
fileprivate func toggle() {
self.animateMenu()
self.showBlur()
self.active = !self.active
self.floatButton.backgroundColor = self.active ? backgroundColorSelected : backgroundColor
self.floatButton.isSelected = self.active
}
fileprivate func animateMenu() {
let rotation = self.active ? 0 : CGFloat(M_PI_4)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.allowAnimatedContent, animations: {
if self.floatButton.imageView?.image == nil {
self.floatButton.transform = CGAffineTransform(rotationAngle: rotation)
}
self.showActive(false)
}, completion: {completed in
if self.active == false {
self.hideBlur()
}
})
}
fileprivate func showActive(_ active: Bool) {
if self.active == active {
self.contentView.alpha = 1.0
if let optionalItems = self.items {
for (index, item) in optionalItems.enumerated() {
let offset = index + 1
let translation = self.itemOffset * offset
item.view.transform = CGAffineTransform(translationX: 0, y: CGFloat(translation))
item.view.alpha = 1
}
}
} else {
self.contentView.alpha = 0.0
if let optionalItems = self.items {
for item in optionalItems {
item.view.transform = CGAffineTransform(translationX: 0, y: 0)
item.view.alpha = 0
}
}
}
}
fileprivate func showBlur() {
self.parentView.insertSubview(self.contentView, belowSubview: self.floatButton)
}
fileprivate func hideBlur() {
self.contentView.removeFromSuperview()
}
/**
Animates the button pressing, by the default this method just scales the button down when it's pressed and returns to its normal size when the button is no longer pressed
- parameter scale: how much the button should be scaled
*/
fileprivate func animatePressingWithScale(_ scale: CGFloat) {
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.allowAnimatedContent, animations: {
self.floatButton.transform = CGAffineTransform(scaleX: scale, y: scale)
}, completion: nil)
}
}
| mit | 27b6a44eddaf2882834883a28c87c9a0 | 39.699248 | 186 | 0.65315 | 5.000462 | false | false | false | false |
didisouzacosta/Spotlight | Spotlight/Class/Control/MoviesController.swift | 1 | 7136 | //
// MoviesController.swift
// Spotlight
//
// Created by Adriano Costa on 24/12/15.
//
//
import UIKit
import CoreSpotlight
import MobileCoreServices
class MoviesController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//
// Constantes
//
let strNameFile = "GamesData"
let strFileType = "plist"
let strCellName = "Cell"
//
// Variáveis
//
var arMovies:Array<Movie> = []
//
// Componentes
//
@IBOutlet weak var tvMovies:UITableView?
override func viewDidLoad() {
super.viewDidLoad()
loadMovies()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
if identifier == "infosMovieSegue" {
if let movieDetailController = segue.destinationViewController as? MovieDetailController {
movieDetailController.movie = sender as? Movie
}
}
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arMovies.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(strCellName, forIndexPath: indexPath) as! MovieCell
let movie = arMovies[indexPath.row]
cell.lblTitle?.text = movie.title
cell.lblCategory?.text = movie.category.joinWithSeparator(", ")
cell.lblInfo?.text = movie.info
cell.lblRating?.text = "\(movie.rating)"
cell.imgMovieImage?.image = UIImage(named: movie.image)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("infosMovieSegue", sender: arMovies[indexPath.row])
}
func setupSearchableContent() {
var searchableItems:Array<CSSearchableItem> = []
for movie in arMovies {
let imagePathParts = movie.image.componentsSeparatedByString(".")
let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
searchableItemAttributeSet.title = movie.title
searchableItemAttributeSet.thumbnailURL = NSBundle.mainBundle().URLForResource(imagePathParts.first, withExtension: imagePathParts.last)
searchableItemAttributeSet.contentDescription = movie.info
searchableItemAttributeSet.keywords = movie.keywords + movie.category + movie.plataform
//
// Aqui criamos o objeto que será indexado pelo SO. Temos que nos atentar aqui que o parâmetro "uniqueIdentifier" será usado posteriormente para identificar o objeto que sofreu interação com o usuário na busca.
//
let searchableItem = CSSearchableItem(uniqueIdentifier: "com.Spotlight.\(movie.id)", domainIdentifier: "games", attributeSet: searchableItemAttributeSet)
searchableItems.append(searchableItem)
}
//
// Após termos criado a lista de itens que serão indexados, precisamos ter o cuidade de também remover os itens que não existem mais em nosso app e removelos da indexação. Esse ponto e feito de forma manual, então nesse ponto vamos usar "deleteSearchableItemsWithDomainIdentifiers" que remover todos os itens que estão indexados no domain "games" e em seguida adicionamos os novos valores. Nessa etapa também temos a opção de remover todos os itens indexados "deleteAllSearchableItemsWithCompletionHandler" ou remover alguns valores especificos "deleteSearchableItemsWithIdentifiers".
//
CSSearchableIndex.defaultSearchableIndex().deleteSearchableItemsWithDomainIdentifiers(["games"]) { (error) -> Void in
if error != nil {
print(error!.localizedDescription)
} else {
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { (error) -> Void in
if error != nil {
print(error!.localizedDescription)
}
}
}
}
}
override func restoreUserActivityState(activity: NSUserActivity) {
if activity.activityType == CSSearchableItemActionType {
if let userInfo = activity.userInfo {
let selectedMovie = userInfo[CSSearchableItemActivityIdentifier] as! String
let idSelectdMovie = Int(selectedMovie.componentsSeparatedByString(".").last!)!
let movies = arMovies.filter({ (movie) -> Bool in
return movie.id == idSelectdMovie
})
if let movie = movies.first {
performSegueWithIdentifier("infosMovieSegue", sender: movie)
}
}
}
}
func loadMovies() {
if let path = NSBundle.mainBundle().pathForResource(strNameFile, ofType: strFileType) {
if let movies = NSArray(contentsOfFile: path) {
for movie in movies {
let m = Movie(
id: (movie.valueForKey("ID") as? Int) ?? 0,
image: (movie.valueForKey("Image") as? String) ?? String(),
title: (movie.valueForKey("Title") as? String) ?? String(),
info: (movie.valueForKey("Info") as? String) ?? String(),
category: (movie.valueForKey("Category") as! String).componentsSeparatedByString(", "),
developer: (movie.valueForKey("Developer") as? String) ?? String(),
keywords: (movie.valueForKey("Keywords") as! String).componentsSeparatedByString(", "),
plataform: (movie.valueForKey("Plataform") as! String).componentsSeparatedByString(", "),
rating: (movie.valueForKey("Rating") as? Int) ?? 0,
active: (movie.valueForKey("Active") as? Bool) ?? false
)
arMovies.append(m)
}
//
// Exibimos apenas o games que estão ativos
//
arMovies = arMovies.filter { $0.active == true }
arMovies.sortInPlace { $0.rating > $1.rating }
tvMovies?.reloadData()
setupSearchableContent()
}
}
}
}
| apache-2.0 | 7f9729fee13ddf18db81bcb6a521c414 | 43.204969 | 592 | 0.603344 | 5.303279 | false | false | false | false |
byvapps/ByvUtils | ByvUtils/Classes/UINavigationController+extension.swift | 1 | 6005 | //
// UINavigationViewController+extension.swift
// Pods
//
// Created by Adrian Apodaca on 25/5/17.
//
//
import Foundation
public class PreNavData {
static public var assoKey: UInt8 = 0
public var color:UIColor? = nil
public var image:UIImage? = nil
public var shadowImage:UIImage? = nil
public var tint:UIColor? = nil
public var barStyle:UIBarStyle = .default
public var trans:Bool = true
var loaded:Bool = false
let gradient = CAGradientLayer()
var gradientView:UIView = UIView()
var navColor:UIColor = UIColor(white: 0.98, alpha: 0.84)
var currentAlpha:CGFloat = 0.0
}
public extension UINavigationController {
var preNavData: PreNavData {
get {
return associatedObject(base:self, key: &PreNavData.assoKey)
{ return PreNavData() } // Set the initial value of the var
}
set { associateObject(base:self, key: &PreNavData.assoKey, value: newValue) }
}
public func prepareForAlphaUpdates() {
if preNavData.loaded {
self.resetFromAlphaUpdates()
}
NotificationCenter.default.addObserver(self, selector: #selector(self.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
let pre = PreNavData()
pre.color = self.navigationBar.backgroundColor
pre.image = self.navigationBar.backgroundImage(for: .default)
pre.shadowImage = self.navigationBar.shadowImage
pre.trans = self.navigationBar.isTranslucent
pre.tint = self.navigationBar.tintColor
pre.barStyle = self.navigationBar.barStyle
pre.navColor = self.navigationBar.barTintColor ?? UIColor(white: 0.98, alpha: 0.84)
pre.loaded = true
var frame = self.navigationBar.bounds
if #available(iOS 11.0, *) {
print("safeAreaInsets: \(self.view.safeAreaInsets)")
} else {
// Fallback on earlier versions
}
if !UIApplication.shared.isStatusBarHidden {
frame.origin.y -= UIApplication.shared.statusBarFrame.height
frame.size.height += UIApplication.shared.statusBarFrame.height
}
pre.gradientView.frame = frame
pre.gradient.frame = pre.gradientView.bounds
pre.gradient.colors = [UIColor(white: 0, alpha: 0.4).cgColor,
UIColor(white: 0, alpha: 0.0).cgColor]
pre.gradientView.backgroundColor = UIColor.clear
pre.gradientView.layer.insertSublayer(pre.gradient, at: 0)
self.navigationBar.addSubview(pre.gradientView)
pre.gradientView.isUserInteractionEnabled = false
self.navigationBar.sendSubview(toBack: pre.gradientView)
self.preNavData = pre
self.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.isTranslucent = true
}
public func resetFromAlphaUpdates() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
self.navigationBar.backgroundColor = preNavData.color
self.navigationBar.setBackgroundImage(preNavData.image, for: .default)
self.navigationBar.shadowImage = preNavData.shadowImage
self.navigationBar.isTranslucent = preNavData.trans
self.navigationBar.tintColor = preNavData.tint
self.navigationBar.barStyle = preNavData.barStyle
preNavData.gradientView.removeFromSuperview()
preNavData = PreNavData()
}
public func updateNavAlpha() {
self.updateNavAlpha(preNavData.currentAlpha)
}
public func updateNavAlpha(_ alpha: CGFloat) {
if !self.preNavData.loaded {
self.prepareForAlphaUpdates()
}
if alpha > 0.0 {
self.navigationBar.setBackgroundImage(preNavData.image, for: .default)
self.navigationBar.shadowImage = preNavData.shadowImage
self.navigationBar.tintColor = preNavData.tint
self.navigationBar.barStyle = preNavData.barStyle
} else {
self.navigationBar.tintColor = UIColor.white
self.navigationBar.barStyle = .black
self.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.isTranslucent = true
}
preNavData.currentAlpha = alpha
preNavData.gradientView.alpha = 1 - preNavData.currentAlpha
updateBakImageAlpha()
}
@objc func rotated() {
var frame = self.navigationBar.bounds
if !UIApplication.shared.isStatusBarHidden {
frame.size.height += UIApplication.shared.statusBarFrame.height
frame.origin.y -= UIApplication.shared.statusBarFrame.height
}
preNavData.gradient.frame = frame
preNavData.gradientView.frame = frame
updateBakImageAlpha()
}
func updateBakImageAlpha() {
if preNavData.currentAlpha == 1.0 {
self.navigationBar.isTranslucent = preNavData.trans
self.navigationBar.backgroundColor = preNavData.color
} else {
self.navigationBar.isTranslucent = true
var finalAlpha = preNavData.currentAlpha
if preNavData.trans {
finalAlpha -= 0.025
}
if let img = preNavData.image {
self.navigationBar.setBackgroundImage(img.alpha(preNavData.currentAlpha), for: .default)
} else {
self.navigationBar.setBackgroundImage(preNavData.navColor.withAlphaComponent(finalAlpha).asImage(self.navigationBar.bounds.size), for: .default)
}
if let color = preNavData.color {
self.navigationBar.backgroundColor = color.withAlphaComponent(finalAlpha)
}
}
}
}
| mit | 8831cae96ad548f9ae7ca1cb31388d64 | 37.248408 | 160 | 0.646128 | 4.735804 | false | false | false | false |
izqui/Taylor | Sources/Example/main.swift | 1 | 667 | import Taylor
let server = Taylor.Server()
server.use("*", Middleware.requestLogger { print($0) })
server.get("/") {
r, s in
s.bodyString = "<html><body><form method=\"POST\">Name: <input type=\"text\" name=\"name\"/><input type=\"submit\"/></form></body></html>"
s.headers["Content-Type"] = "text/html"
return .Send
}
server.post("/", Middleware.bodyParser(), {
r, s in
let name = r.body["name"] ?? "<unknown>"
s.bodyString = "Hi \(name)"
return .Send
})
let port = 3002
do {
print("Staring server on port: \(port)")
try server.serveHTTP(port: port, forever: true)
} catch let e {
print("Server start failed \(e)")
}
| mit | 192613ed91aaf9be764f512a7898e757 | 23.703704 | 142 | 0.5997 | 3.318408 | false | false | false | false |
PerfectExamples/Perfect-TensorFlow-Demo-Vision | Sources/PerfectTensorFlowDemo/main.swift | 1 | 5898 | //
// main.swift
// Perfect-TensorFlow-Demo-Computer Vision
//
// Created by Rockford Wei on 2017-06-19.
// Copyright © 2017 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2017 - 2018 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import Foundation
import PerfectLib
import PerfectTensorFlow
import PerfectHTTP
import PerfectHTTPServer
typealias TF = TensorFlow
class LabelImage {
let def: TF.GraphDef
public init(_ model:Data) throws {
def = try TF.GraphDef(serializedData: model)
}
public func match(image: Data) throws -> (Int, Int) {
let g = try TF.Graph()
_ = try g.import(definition: def)
let normalized = try constructAndExecuteGraphToNormalizeImage(g, imageBytes: image)
let possibilities = try executeInceptionGraph(g, image: normalized)
guard let m = possibilities.max(), let i = possibilities.firstIndex(of: m) else {
throw TF.Panic.INVALID
}//end guard
return (i, Int(m * 100))
}
private func executeInceptionGraph(_ g: TF.Graph, image: TF.Tensor) throws -> [Float] {
let results = try g.runner().feed("input", tensor: image).fetch("output").run()
guard results.count > 0 else { throw TF.Panic.INVALID }
let result = results[0]
guard result.dimensionCount == 2 else { throw TF.Panic.INVALID }
let shape = result.dim
guard shape[0] == 1 else { throw TF.Panic.INVALID }
let res: [Float] = try result.asArray()
return res
}//end exec
public func constructAndExecuteGraphToNormalizeImage(_ g: TF.Graph, imageBytes: Data) throws -> TF.Tensor {
let H:Int32 = 224
let W:Int32 = 224
let mean:Float = 117
let scale:Float = 1
let input = try g.constant(name: "input2", value: imageBytes)
let batch = try g.constant( name: "make_batch", value: Int32(0))
let scale_v = try g.constant(name: "scale", value: scale)
let mean_v = try g.constant(name: "mean", value: mean)
let size = try g.constantArray(name: "size", value: [H,W])
let jpeg = try g.decodeJpeg(content: input, channels: 3)
let cast = try g.cast(value: jpeg, dtype: TF.DataType.dtFloat)
let images = try g.expandDims(input: cast, dim: batch)
let resizes = try g.resizeBilinear(images: images, size: size)
let subbed = try g.sub(x: resizes, y: mean_v)
let output = try g.div(x: subbed, y: scale_v)
let s = try g.runner().fetch(TF.Operation(output)).run()
guard s.count > 0 else { throw TF.Panic.INVALID }
return s[0]
}//end normalize
}
var inceptionModel: LabelImage? = nil
var tags = [String]()
func handler(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let prefix = "data:image/jpeg;base64,"
guard let input = request.postBodyString, input.hasPrefix(prefix),
let b64 = String(input.utf8.dropFirst(prefix.utf8.count)),
let scanner = inceptionModel
else {
response.setHeader(.contentType, value: "text/json")
response.appendBody(string: "{\"value\": \"Invalid Input\"}")
response.completed()
return
}//end
let jpeg = Data.From(b64)
guard let data = Data(base64Encoded: jpeg) else {
response.setHeader(.contentType, value: "text/json")
response.appendBody(string: "{\"value\": \"Input is not a valid jpeg\"}")
response.completed()
return
}//end guard
do {
let result = try scanner.match(image: data)
guard result.0 > -1 && result.0 < tags.count else {
response.setHeader(.contentType, value: "text/json")
response.appendBody(string: "{\"value\": \"what is this???\"}")
response.completed()
return
}//end
let tag = tags[result.0]
let p = result.1
response.setHeader(.contentType, value: "text/json")
response.appendBody(string: "{\"value\": \"Is it a \(tag)? (Possibility: \(p)%)\"}")
response.completed()
print(tag, p)
}catch {
response.setHeader(.contentType, value: "text/json")
response.appendBody(string: "{\"value\": \"\(error)\"}")
response.completed()
print("\(error)")
}
}
}
let confData = [
"servers": [
[
"name":"localhost",
"port":8080,
"routes":[
["method":"post", "uri":"/recognize", "handler":handler],
["method":"get", "uri":"/**", "handler":PerfectHTTPServer.HTTPHandler.staticFiles,
"documentRoot":"./webroot",
"allowResponseFilters":true]
],
"filters":[
[
"type":"response",
"priority":"high",
"name":PerfectHTTPServer.HTTPFilter.contentCompression,
]
]
]
]
]
do {
let modelPath = "/tmp/tensorflow_inception_graph.pb"
let tagPath = "/tmp/imagenet_comp_graph_label_strings.txt"
let fModel = File(modelPath)
let fTag = File(tagPath)
if !fModel.exists || !fTag.exists {
let modelPath = "https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip"
print("please download model from \(modelPath)")
exit(-1)
}//end if
try fModel.open(.read)
let modelBytes = try fModel.readSomeBytes(count: fModel.size)
guard modelBytes.count == fModel.size else {
print("model file reading failed")
exit(-3)
}//end guard
fModel.close()
try fTag.open(.read)
let lines = try fTag.readString()
tags = lines.split(separator: "\n").map { String(describing: $0) }
try TF.Open()
inceptionModel = try LabelImage( Data(modelBytes) )
print("library ready")
try HTTPServer.launch(configurationData: confData)
}catch {
print("fault: \(error)")
}
| apache-2.0 | 10ff250e2b2e737b6c6f33f5511d6f95 | 32.890805 | 109 | 0.626081 | 3.741751 | false | false | false | false |
ikhsan/FutureOfRamadhan | FutureRamadhans/DataCollection.swift | 1 | 2138 |
import Foundation
import CoreLocation
import BAPrayerTimes
struct RamadhanSummary {
let method = BAPrayerMethod.MCW
let madhab = BAPrayerMadhab.Hanafi
let firstDay: NSDate
let lastDay: NSDate
let placemark: CLPlacemark
var prayerTime: BAPrayerTimes? { return prayerTimesForDate(firstDay) }
var duration: Double { return getDuration(firstDay) }
}
// MARK: Private methods
private extension RamadhanSummary {
private func prayerTimesForDate(date: NSDate) -> BAPrayerTimes? {
guard let latitude = placemark.location?.coordinate.latitude,
let longitude = placemark.location?.coordinate.longitude,
let timezone = placemark.timeZone else {
return nil
}
return BAPrayerTimes(
date: firstDay,
latitude: latitude,
longitude: longitude,
timeZone: timezone,
method: method,
madhab: madhab
)
}
private func getDuration(date: NSDate) -> Double {
guard let prayerTime = prayerTimesForDate(date) else {
return 0
}
let duration = prayerTime.maghribTime.timeIntervalSinceReferenceDate - prayerTime.fajrTime.timeIntervalSinceReferenceDate
return (duration / 3600.0)
}
}
// MARK: Create summaries
extension RamadhanSummary {
static func summariesForCity(city: String, initialYear: Int, durationInYears: Int, completionHandler: ([RamadhanSummary]) -> Void) {
CLGeocoder().geocodeAddressString(city) { p, error in
guard let placemark = p?.first else {
completionHandler([])
return
}
let summaries = (initialYear..<(initialYear + durationInYears)).flatMap { year -> RamadhanSummary? in
let dates = NSDate.rmdn_ramadhanDaysForHijriYear(year)
guard let firstDay = dates.first, let lastDay = dates.last else { return nil }
return RamadhanSummary(firstDay: firstDay, lastDay: lastDay, placemark: placemark)
}
completionHandler(summaries)
}
}
} | mit | 572e5d21df76308650c9b86c2be86a33 | 29.126761 | 136 | 0.637979 | 4.617711 | false | false | false | false |
allevato/SwiftCGI | Sources/SwiftCGI/BufferingInputStream.swift | 1 | 4760 | // Copyright 2015 Tony Allevato
//
// 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.
/// An input stream that internally loads chunks of data into an internal buffer and serves read
/// requests from it to improve performance.
public class BufferingInputStream: InputStream {
/// The default size of the buffer.
private static let defaultBufferSize = 16384
/// The input stream from which this buffering stream reads its input.
private let inputStream: InputStream
/// The buffer that holds data read from the underlying stream.
private var inputBuffer: [UInt8]
/// The number of bytes in the input buffer that are actually filled with valid data.
private var inputBufferCount: Int
/// The index into the buffer at which the next data will be read.
private var inputBufferOffset: Int
/// Creates a new buffering input stream that reads from the given input stream, optionally
/// specifying the internal buffer size.
public init(
inputStream: InputStream, bufferSize: Int = BufferingInputStream.defaultBufferSize) {
self.inputStream = inputStream
inputBuffer = [UInt8](count: bufferSize, repeatedValue: 0)
inputBufferCount = 0
inputBufferOffset = 0
}
public func read(inout buffer: [UInt8], offset: Int, count: Int) throws -> Int {
if count == 0 {
return 0
}
// Repeatedly read from the stream until we've gotten the requested number of bytes or reached
// the end of the stream.
var readSoFar = 0
while readSoFar < count {
let remaining = count - readSoFar
do {
let readThisTime = try readFromUnderlyingStream(
&buffer, offset: offset + readSoFar, count: remaining)
readSoFar += readThisTime
if readThisTime == 0 {
return readSoFar
}
} catch IOError.EOF {
// Only allow EOF to be thrown if it's the first time we're trying to read. If we get an EOF
// from the underlying stream after successfully reading some data, we just return the count
// that was actually read.
if readSoFar > 0 {
return readSoFar
}
throw IOError.EOF
}
}
return readSoFar
}
public func seek(offset: Int, origin: SeekOrigin) throws -> Int {
// TODO: Support seeking.
throw IOError.Unsupported
}
public func close() {
inputStream.close()
}
/// Reads data at most once from the underlying stream, filling the buffer if necessary.
///
/// - Parameter buffer: The array into which the data should be written.
/// - Parameter offset: The byte offset in `buffer` into which to start writing data.
/// - Parameter count: The maximum number of bytes to read from the stream.
/// - Returns: The number of bytes that were actually read. This can be less than the requested
/// number of bytes if that many bytes are not available, or 0 if the end of the stream is
/// reached.
/// - Throws: `IOError` if an error other than reaching the end of the stream occurs.
private func readFromUnderlyingStream(
inout buffer: [UInt8], offset: Int, count: Int) throws -> Int {
var available = inputBufferCount - inputBufferOffset
if available == 0 {
// If there is nothing currently in the buffer and the requested count is at least as large as
// the buffer, then just read the data directly from the underlying stream. This is acceptable
// since the purpose of the buffer is to reduce I/O thrashing, and breaking a larger read into
// multiple smaller ones would have the opposite effect.
if count >= inputBuffer.count {
return try inputStream.read(&buffer, offset: offset, count: count)
}
// Fill the buffer by reading from the underlying stream.
inputBufferCount = try inputStream.read(&inputBuffer, offset: 0, count: inputBuffer.count)
inputBufferOffset = 0
available = inputBufferCount
if inputBufferCount == 0 {
throw IOError.EOF
}
}
let countToCopy = (available < count) ? available : count
buffer.replaceRange(offset..<offset + countToCopy,
with: inputBuffer[inputBufferOffset..<inputBufferOffset + countToCopy])
inputBufferOffset += countToCopy
return countToCopy
}
}
| apache-2.0 | a2745e206b0e5de517a53fe0e4c6e7fd | 37.387097 | 100 | 0.694328 | 4.675835 | false | false | false | false |
kostickm/mobileStack | MobileStack/NovaViewController.swift | 1 | 12128 | /**
* Copyright IBM Corporation 2016
*
* 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 Foundation
public let novaport = Config.NOVAPORT
public let tenantId = Config.TENANTID
func getServers(complete: @escaping ([Server]) -> ()) {
getAuthToken { keystoneToken in
// Create Request
var novaReq = URLRequest(url: URL(string: "http://\(controller):\(novaport)/v2.1/servers/detail")!)
novaReq.httpMethod = "GET"
novaReq.allHTTPHeaderFields = ["Content-Type": "application/json", "X-Auth-Token": "\(keystoneToken)"]
let session = URLSession.shared
// Perform Request
session.dataTask(with: novaReq) {result, res, err in
guard let result = result else {
print("No result")
return
}
// Convert results to a JSON object
let json = JSON(data: result)
//print(json)
var serverList = [Server]()
for (_, item) in json["servers"] {
let serverInfo = Server(name: item["name"].string!, id: item["id"].string!, status: item["status"].string!)
serverList.append(serverInfo)
}
complete(serverList)
}.resume()
}
}
func deleteServer(serverID: String) {
getAuthToken { keystoneToken in
// Create Request
var req = URLRequest(url: URL(string: "http://\(controller):\(novaport)/v2.1/servers/\(serverID)")!)
req.httpMethod = "DELETE"
req.allHTTPHeaderFields = ["Content-Type": "application/json", "X-Auth-Token": "\(keystoneToken)"]
//print("Headers: \(req.allHTTPHeaderFields)")
let session = URLSession.shared
// Perform Request
session.dataTask(with: req) {result, res, err in
guard result != nil else {
print("No result")
return
}
// Convert results to a JSON object
//let json = JSON(data: result!)
//print(json)
}.resume()
}
}
func createServer(name: String, imageId: String, flavorId: String) {
getAuthToken { keystoneToken in
let parameters:[String: Any] = ["server": [
"name": name,
"imageRef": imageId,
"flavorRef": flavorId,
"networks": [["uuid": "0a4ef5ac-0638-451b-8dbb-ae5bda7ae5ba"]]
]
]
// Create Request
var novaReq = URLRequest(url: URL(string: "http://\(controller):\(novaport)/v2.1/servers")!)
novaReq.httpMethod = "POST"
if JSONSerialization.isValidJSONObject(parameters) == false {
print("Invalid JSON")
}
do {
novaReq.httpBody = try JSONSerialization.data(withJSONObject: parameters,
options: JSONSerialization.WritingOptions())
} catch {
print("Could not create JSON body")
}
novaReq.allHTTPHeaderFields = ["Content-Type": "application/json", "X-Auth-Token": "\(keystoneToken)"]
let session = URLSession.shared
// Perform Request
session.dataTask(with: novaReq) {result, res, err in
guard result != nil else {
print("No result")
return
}
// Convert results to a JSON object
//let json = JSON(data: result)
}.resume()
}
}
func getFlavors(complete: @escaping ([Flavor]) -> ()) {
getAuthToken { keystoneToken in
// Create Request
var novaReq = URLRequest(url: URL(string: "http://\(controller):\(novaport)/v2.1/flavors")!)
novaReq.httpMethod = "GET"
novaReq.allHTTPHeaderFields = ["Content-Type": "application/json", "X-Auth-Token": "\(keystoneToken)"]
let session = URLSession.shared
// Perform Request
session.dataTask(with: novaReq) {result, res, err in
guard let result = result else {
print("No result")
return
}
// Convert results to a JSON object
let json = JSON(data: result)
var flavorList = [Flavor]()
for (_, item) in json["flavors"] {
let serverInfo = Flavor(name: item["name"].string!, id: item["id"].string!)
flavorList.append(serverInfo)
}
complete(flavorList)
}.resume()
}
}
func rebootServer(serverId: String) {
getAuthToken { keystoneToken in
let parameters:[String: Any] = ["reboot": [
"type": "HARD"
]
]
// Create Request
var novaReq = URLRequest(url: URL(string: "http://\(controller):\(novaport)/v2.1/\(tenantId)/servers/\(serverId)/action")!)
novaReq.httpMethod = "POST"
if JSONSerialization.isValidJSONObject(parameters) == false {
print("Invalid JSON")
}
do {
novaReq.httpBody = try JSONSerialization.data(withJSONObject: parameters,
options: JSONSerialization.WritingOptions())
} catch {
print("Could not create JSON body")
}
novaReq.allHTTPHeaderFields = ["Content-Type": "application/json", "X-Auth-Token": "\(keystoneToken)"]
let session = URLSession.shared
// Perform Request
session.dataTask(with: novaReq) {result, res, err in
guard result != nil else {
print("No result")
return
}
// Convert results to a JSON object
//let json = JSON(data: result)
}.resume()
}
}
func startServer(serverId: String) {
getAuthToken { keystoneToken in
let parameters:[String: Any] = [ "os-start": "null" ]
// Create Request
var novaReq = URLRequest(url: URL(string: "http://\(controller):\(novaport)/v2.1/\(tenantId)/servers/\(serverId)/action")!)
novaReq.httpMethod = "POST"
if JSONSerialization.isValidJSONObject(parameters) == false {
print("Invalid JSON")
}
do {
novaReq.httpBody = try JSONSerialization.data(withJSONObject: parameters,
options: JSONSerialization.WritingOptions())
} catch {
print("Could not create JSON body")
}
novaReq.allHTTPHeaderFields = ["Content-Type": "application/json", "X-Auth-Token": "\(keystoneToken)"]
let session = URLSession.shared
// Perform Request
session.dataTask(with: novaReq) {result, res, err in
guard result != nil else {
print("No result")
return
}
// Convert results to a JSON object
//let json = JSON(data: result)
}.resume()
}
}
func stopServer(serverId: String) {
getAuthToken { keystoneToken in
let parameters:[String: Any] = [ "os-stop": "null" ]
// Create Request
var novaReq = URLRequest(url: URL(string: "http://\(controller):\(novaport)/v2.1/\(tenantId)/servers/\(serverId)/action")!)
novaReq.httpMethod = "POST"
if JSONSerialization.isValidJSONObject(parameters) == false {
print("Invalid JSON")
}
do {
novaReq.httpBody = try JSONSerialization.data(withJSONObject: parameters,
options: JSONSerialization.WritingOptions())
} catch {
print("Could not create JSON body")
}
novaReq.allHTTPHeaderFields = ["Content-Type": "application/json", "X-Auth-Token": "\(keystoneToken)"]
let session = URLSession.shared
// Perform Request
session.dataTask(with: novaReq) {result, res, err in
guard result != nil else {
print("No result")
return
}
// Convert results to a JSON object
//let json = JSON(data: result)
}.resume()
}
}
func attachVolumeToServer(serverId: String, volumeId: String) {
getAuthToken { keystoneToken in
let parameters:[String: Any] = ["volumeAttachment": [
"volumeId": volumeId,
]
]
// Create Request
var novaReq = URLRequest(url: URL(string: "http://\(controller):\(novaport)/v2.1/\(tenantId)/servers/\(serverId)/os-volume_attachments")!)
novaReq.httpMethod = "POST"
if JSONSerialization.isValidJSONObject(parameters) == false {
print("Invalid JSON")
}
do {
novaReq.httpBody = try JSONSerialization.data(withJSONObject: parameters,
options: JSONSerialization.WritingOptions())
} catch {
print("Could not create JSON body")
}
novaReq.allHTTPHeaderFields = ["Content-Type": "application/json", "X-Auth-Token": "\(keystoneToken)"]
let session = URLSession.shared
// Perform Request
session.dataTask(with: novaReq) {result, res, err in
guard result != nil else {
print("No result")
return
}
// Convert results to a JSON object
//let json = JSON(data: result)
}.resume()
}
}
func listVolumeAttachments(serverId: String, complete: @escaping ([Attach]) -> ()) {
getAuthToken { keystoneToken in
// Create Request
var novaReq = URLRequest(url: URL(string: "http://\(controller):\(novaport)/v2.1/\(tenantId)/servers/\(serverId)/os-volume_attachments")!)
novaReq.httpMethod = "GET"
novaReq.allHTTPHeaderFields = ["Content-Type": "application/json", "X-Auth-Token": "\(keystoneToken)"]
let session = URLSession.shared
// Perform Request
session.dataTask(with: novaReq) {result, res, err in
guard let result = result else {
print("No result")
return
}
// Convert results to a JSON object
let json = JSON(data: result)
var attachmentList = [Attach]()
if json["volumeAttachments"].exists() {
for (_, item) in json["volumeAttachments"] {
let volumeInfo = Attach(id: item["id"].string!, serverId: item["serverId"].string!, volumeId: item["volumeId"].string!, device: item["device"].string!)
attachmentList.append(volumeInfo)
}
}
complete(attachmentList)
}.resume()
}
}
func detachVolumeToServer(serverId: String, volumeId: String, attachment: String) {
getAuthToken { keystoneToken in
// Create Request
var novaReq = URLRequest(url: URL(string: "http://\(controller):\(novaport)/v2.1/\(tenantId)/servers/\(serverId)/os-volume_attachments/\(attachment)")!)
novaReq.httpMethod = "DELETE"
novaReq.allHTTPHeaderFields = ["Content-Type": "application/json", "X-Auth-Token": "\(keystoneToken)"]
let session = URLSession.shared
// Perform Request
session.dataTask(with: novaReq) {result, res, err in
guard result != nil else {
print("No result")
return
}
}.resume()
}
}
| apache-2.0 | 76bbcd33b7196420ecac3206504d7f22 | 31.602151 | 171 | 0.550379 | 4.686244 | false | false | false | false |
springwong/SnapKitten | Example/SnapKitten/KittenPlayground.playground/Contents.swift | 1 | 1179 | //: Playground - noun: a place where people can play
import UIKit
import SnapKitten
import PlaygroundSupport
let virtualView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 100))
virtualView.backgroundColor = UIColor.gray
PlaygroundPage.current.liveView = virtualView
let iv = UIImageView()
iv.backgroundColor = UIColor.red
let lblA = UILabel()
lblA.text = "Hello World"
lblA.backgroundColor = UIColor.blue
let iv2 = UIImageView()
iv2.backgroundColor = UIColor.red
let iv3 = UIImageView()
iv3.backgroundColor = UIColor.blue
let lbl2 = UILabel()
lbl2.backgroundColor = UIColor.green
lbl2.text = "short text"
let simpleComponent = Kitten.horizontal().from()
.add(iv).size(40)
.add(lblA).itemOffset(10)
.build()
simpleComponent.backgroundColor = UIColor.green
let threeComponentExample = Kitten.horizontal()
.from().isAlignDirectionEnd(true).defaultAlignment(.center)
.add(iv2).size(40)
.add(lbl2).fillParent()
.add(iv3).size(60).condition({ () -> Bool in
return false
})
.build()
threeComponentExample.backgroundColor = UIColor.orange
Kitten.create(.vertical).from(virtualView)
.add(simpleComponent).align(.start)
.add(threeComponentExample)
.build()
| mit | 62fad27f6a1484e31c3a8f621cc8e864 | 25.795455 | 76 | 0.756573 | 3.540541 | false | false | false | false |
marcelobusico/reddit-ios-app | Reddit-App/Reddit-App/ListReddits/ViewCell/RedditViewCell.swift | 1 | 1483 | //
// RedditViewCell.swift
// Reddit-App
//
// Created by Marcelo Busico on 13/2/17.
// Copyright © 2017 Busico. All rights reserved.
//
import UIKit
class RedditViewCell: UITableViewCell {
// MARK: - Constants
private let thumbnailWidth: CGFloat = 80
// MARK: - Outlets
@IBOutlet weak var thumbnailImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var commentsLabel: UILabel!
// MARK: - Properties
var model: RedditModel? {
didSet {
refreshView()
}
}
// MARK: - Private methods
private func refreshView() {
setupThumbnail(withImage: nil)
accessoryType = .none
selectionStyle = .none
guard let model = self.model else {
titleLabel.text = String()
authorLabel.text = String()
dateLabel.text = String()
commentsLabel.text = String()
return
}
titleLabel.text = model.title
authorLabel.text = "By \(model.author)"
dateLabel.text = "Submitted \(model.formattedTimeSinceSubmissions())"
commentsLabel.text = "\(model.commentsCount) comments"
if model.imageURL != nil {
accessoryType = .disclosureIndicator
selectionStyle = .default
}
}
func setupThumbnail(withImage image: UIImage?) {
var thumbnail = image
if thumbnail == nil {
thumbnail = UIImage(named: "noImage")
}
thumbnailImageView.image = thumbnail
}
}
| apache-2.0 | 9a0c9f41ef5c05dea5f52ca77247ed14 | 22.15625 | 73 | 0.666667 | 4.423881 | false | false | false | false |
svachmic/ios-url-remote | URLRemote/Classes/Helpers/MaterialExtension.swift | 1 | 2298 | //
// MaterialExtension.swift
// URLRemote
//
// Created by Michal Švácha on 29/05/2017.
// Copyright © 2017 Svacha, Michal. All rights reserved.
//
import Foundation
import Material
import Motion
/// Extension for FABMenu used for adding categories and entries.
extension FABMenu {
/// Toggles the menu open/close with an animation.
func toggle() {
var angle: CGFloat = 0.0
if self.isOpened {
self.close()
for v in self.subviews {
(v as? FABMenuItem)?.hideTitleLabel()
}
} else {
angle = 45.0
self.open()
for v in self.subviews {
(v as? FABMenuItem)?.showTitleLabel()
}
}
let animations: [MotionAnimation] = [.rotate(angle), .duration(0.1)]
self.subviews.first?.animate(animations)
}
}
/// Factory class that generates Material UI componenets used in the application.
class MaterialFactory {
/// Generates a FlatButton with given title.
///
/// - Returns: FlatButton instance with pre-set design properties.
private class func flatButton(title: String) -> FlatButton {
let button = FlatButton(title: title)
button.apply(Stylesheet.General.flatButton)
return button
}
/// Generates a cancel button used in ToolbarController as a left view.
///
/// - Returns: FlatButton instance with pre-set design properties.
class func cancelButton() -> FlatButton {
return flatButton(title: NSLocalizedString("CANCEL", comment: ""))
}
/// Generates a close button used in ToolbarController as a left view.
///
/// - Returns: FlatButton instance with pre-set design properties.
class func closeButton() -> FlatButton {
return flatButton(title: NSLocalizedString("CLOSE", comment: ""))
}
/// Generates an icon button with supplied image.
///
/// - Parameter image: Image to set as the icon on the button.
/// - Returns: IconButton instance with pre-set design properties.
class func genericIconButton(image: UIImage?) -> IconButton {
let button = IconButton(image: image, tintColor: .white)
button.pulseColor = .white
return button
}
}
| apache-2.0 | 536a1dff4c6fef638b7eaad630ec1448 | 30.438356 | 81 | 0.621351 | 4.741736 | false | false | false | false |
samantharachelb/todolist | Pods/OctoKit.swift/OctoKit/Label.swift | 1 | 1326 | #if os(OSX)
import Cocoa
typealias Color = NSColor
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit
typealias Color = UIColor
#endif
extension Color {
convenience init?(hexTriplet hex: String) {
var hexChars = hex.characters
let red = Int(String(hexChars.prefix(2)), radix: 16)
hexChars = hexChars.dropFirst(2)
let green = Int(String(hexChars.prefix(2)), radix: 16)
hexChars = hexChars.dropFirst(2)
let blue = Int(String(hexChars), radix: 16)
if let red = red, let green = green, let blue = blue {
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1)
} else {
return nil
}
}
}
@objc open class Label: NSObject {
open var url: URL?
open var name: String?
#if os(OSX)
open var color: NSColor?
#elseif os(iOS) || os(tvOS) || os(watchOS)
public var color: UIColor?
#endif
public init(_ json: [String: AnyObject]) {
if let urlString = json["url"] as? String, let url = URL(string: urlString) {
self.url = url
}
name = json["name"] as? String
if let colorString = json["color"] as? String {
color = Color(hexTriplet: colorString)
}
}
}
| mit | e6442d559b9b5cddb8d7dbdb82dbdd56 | 29.837209 | 118 | 0.574661 | 3.67313 | false | false | false | false |
bsorrentino/slidesOnTV | slides/PageView.swift | 1 | 4628 | //
// PageView.swift
// slides
//
// Created by softphone on 26/09/2016.
// Copyright © 2016 soulsoftware. All rights reserved.
//
import UIKit
import RxRelay
class PageView: UIView, NameDescribable {
@IBOutlet weak var pageImageView: UIImageView!
// MARK: - Shadow management
// MARRK: -
private func addShadow(_ height: Int = 0) {
self.pageImageView.layer.masksToBounds = false
self.pageImageView.layer.shadowColor = UIColor.black.cgColor
self.pageImageView.layer.shadowOpacity = 1
self.pageImageView.layer.shadowOffset = CGSize(width: 0 , height: height)
self.pageImageView.layer.shadowRadius = 10
self.pageImageView.layer.cornerRadius = 0.0
}
private func removeShadow() {
self.pageImageView.layer.masksToBounds = false
self.pageImageView.layer.shadowColor = UIColor.clear.cgColor
self.pageImageView.layer.shadowOpacity = 0.0
self.pageImageView.layer.shadowOffset = .zero
self.pageImageView.layer.shadowRadius = 0.0
self.pageImageView.layer.cornerRadius = 0.0
}
// MARK: - standard lifecycle
// MARK: -
override func didMoveToSuperview() {
}
override func updateConstraints() {
super.updateConstraints()
}
// MARK: - Focus Management
// MARK: -
override var canBecomeFocused : Bool {
return true
}
//
// /// Asks whether the system should allow a focus update to occur.
// override func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool {
// print( "PageView.shouldUpdateFocusInContext:" )
// return true
//
// }
/// Called when the screen’s focusedView has been updated to a new view. Use the animation coordinator to schedule focus-related animations in response to the update.
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator)
{
print( "\(typeName).didUpdateFocusInContext: focused: \(self.isFocused)" );
coordinator.addCoordinatedAnimations(nil) {
// Perform some task after item has received focus
if context.nextFocusedView == self {
self.addShadow()
}
else {
self.removeShadow()
}
}
}
// MARK: - Pointer Management
// MARK: -
fileprivate lazy var pointer:UIView = {
let pointer:UIView = UIView( frame: CGRect(x: 0, y: 0, width: 20, height: 20))
pointer.backgroundColor = UIColor.magenta
pointer.isUserInteractionEnabled = false
pointer.layer.cornerRadius = 10.0
// border
pointer.layer.borderColor = UIColor.lightGray.cgColor
pointer.layer.borderWidth = 1.5
// drop shadow
pointer.layer.shadowColor = UIColor.black.cgColor
pointer.layer.shadowOpacity = 0.8
pointer.layer.shadowRadius = 3.0
pointer.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
return pointer
}()
let showPointerRelay = BehaviorRelay<Bool>( value: false )
var showPointer:Bool = false {
didSet {
if !showPointer {
pointer.removeFromSuperview()
}
else if !oldValue {
pointer.frame.origin = self.center
addSubview(pointer)
}
showPointerRelay.accept( showPointer )
}
}
// MARK: - Touch Handling
// MARK: -
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard showPointer, let firstTouch = touches.first else {
return
}
let locationInView = firstTouch.location(in: firstTouch.view)
var f = pointer.frame
f.origin = locationInView
pointer.frame = f
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard showPointer, let firstTouch = touches.first else {
return
}
let locationInView = firstTouch.location(in: firstTouch.view)
var f = pointer.frame
f.origin = locationInView
pointer.frame = f
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
showPointer = false
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
showPointer = false
}
}
| mit | bb92b6d9f112f4071ded77d19f674899 | 27.20122 | 170 | 0.596757 | 4.914984 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | Source/Core/Code/StreamWaitOperation.swift | 3 | 1237 | //
// StreamWaitOperation.swift
// edX
//
// Created by Akiva Leffert on 6/18/15.
// Copyright (c) 2015 edX. All rights reserved.
//
/// Operation that just waits for a stream to fire, extending the lifetime of the stream.
class StreamWaitOperation<A> : Operation {
private let completion : (Result<A> -> Void)?
private let stream : Stream<A>
private let fireIfAlreadyLoaded : Bool
init(stream : Stream<A>, fireIfAlreadyLoaded : Bool, completion : (Result<A> -> Void)? = nil) {
self.fireIfAlreadyLoaded = fireIfAlreadyLoaded
self.stream = stream
self.completion = completion
}
override func performWithDoneAction(doneAction: () -> Void) {
dispatch_async(dispatch_get_main_queue()) {[weak self] _ in
if let owner = self {
// We should just be able to do this with weak self, but the compiler crashes as of Swift 1.2
owner.stream.listenOnce(owner, fireIfAlreadyLoaded: owner.fireIfAlreadyLoaded) {[weak owner] result in
if !(owner?.cancelled ?? false) {
owner?.completion?(result)
}
doneAction()
}
}
}
}
}
| apache-2.0 | 7ebeb28c35d38c595ce330092f6df8b6 | 33.361111 | 118 | 0.595796 | 4.531136 | false | false | false | false |
NordicSemiconductor/IOS-Pods-DFU-Library | iOSDFULibrary/Classes/Utilities/DFUPackage/Manifest/ManifestFirmwareInfo.swift | 1 | 2154 | /*
* Copyright (c) 2019, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
class ManifestFirmwareInfo: NSObject {
var binFile: String? = nil
var datFile: String? = nil
var valid: Bool {
return binFile != nil // && datFile != nil The init packet was not required before SDK 7.1
}
init(withDictionary aDictionary : Dictionary<String, AnyObject>) {
if aDictionary.keys.contains("bin_file") {
binFile = String(describing: aDictionary["bin_file"]!)
}
if aDictionary.keys.contains("dat_file") {
datFile = String(describing: aDictionary["dat_file"]!)
}
}
}
| bsd-3-clause | b06a71959250e0ae07d9a0d184b05e3c | 42.959184 | 98 | 0.734912 | 4.592751 | false | false | false | false |
Reality-Virtually-Hackathon/Team-2 | WorkspaceAR/Virtual Objects/SharedARObject.swift | 1 | 2831 | //
// SharedARObject.swift
// WorkspaceAR
//
// Created by Joe Crotchett on 10/7/17.
// Copyright © 2017 Apple. All rights reserved.
//
import Foundation
import SceneKit
class SharedARObject: NSObject, NSCoding {
var id: String
var modelName: String
var name:String
var animation: [String]
var transform: SCNMatrix4
var descriptionText: String
var mass: Double
var restitution:Double
init(id: String = "",
name: String,
modelName: String,
animation: [String],
transform: SCNMatrix4, descriptionText: String, mass: Double, restitution:Double) {
if id == ""{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "y-MM-dd H:m:ss.SSSS"
self.id = dateFormatter.string(from: Date()) + "\(CACurrentMediaTime())"
}else{
self.id = id
}
self.modelName = modelName
self.name = name
self.animation = animation
self.transform = transform
self.descriptionText = descriptionText
self.mass = mass
self.restitution = restitution
}
// MARK: NSCoding
required convenience init(coder aDecoder: NSCoder) {
let id = aDecoder.decodeObject(forKey: "id") as! String
let modelName = aDecoder.decodeObject(forKey: "modelName") as! String
let name = aDecoder.decodeObject(forKey: "name") as! String
let animation = aDecoder.decodeObject(forKey: "animation") as! [String]
let transformValue = aDecoder.decodeObject(forKey: "transform") as! [Float]
let transform = SCNMatrix4.matrixFromFloatArray(transformValue: transformValue)
let descriptionText = aDecoder.decodeObject(forKey: "descriptionText") as! String
let mass = aDecoder.decodeObject(forKey: "mass") as! NSNumber
let restitution = aDecoder.decodeObject(forKey: "restitution") as! NSNumber
self.init(
id: id,
name: name,
modelName: modelName,
animation: animation,
transform: transform,
descriptionText: descriptionText,
mass: mass.doubleValue,
restitution:restitution.doubleValue
)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.id, forKey: "id")
aCoder.encode(self.modelName, forKey: "modelName")
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.animation, forKey: "animation")
aCoder.encode(self.transform.toFloatArray(), forKey: "transform")
aCoder.encode(descriptionText, forKey: "descriptionText")
aCoder.encode(NSNumber.init(value: mass), forKey: "mass")
aCoder.encode(NSNumber.init(value: restitution), forKey: "restitution")
}
}
| mit | fa848d507214e66ac534dcdc099a351e | 33.512195 | 91 | 0.626148 | 4.609121 | false | false | false | false |
KTMarc/Marvel-Heroes | Marvel Heroes/Extensions/URL+fetchImage.swift | 1 | 1489 | //
// NSURL+fetchImage.swift
// Marvel Heroes
//
// Created by Marc Humet on 8/8/16.
// Copyright © 2016 SPM. All rights reserved.
//
import Foundation
import UIKit
/**
Retrieves a pre-cached image, or downloads it if it isn't cached.
We use the URL as a key to save the image in the cache and be able to retrieve afterwards.
*/
extension URL {
/**
Returns the image using it's URL as key
It is meant to be called before calling fetchImage.
returns: UIImage or Nil if we don't have the image in the cache
*/
var cachedImage: UIImage? {
return apiClient.manager.getCache().object(forKey: absoluteString as NSString)
}
/**
Fetches the image from the network and stores it in the cache if successful.
Only calls completion on the main thread on successful image download.
*/
func fetchImage(completion: @escaping ImageCacheCompletion) {
let task = URLSession.shared.dataTask(with:self) {
data, response, error in
if error == nil {
if let dataa = data,
let image = UIImage(data: dataa) {
apiClient.manager.getCache().setObject(
image,
forKey: self.absoluteString as NSString)
DispatchQueue.main.async() {
completion(image)
}
}
}
}
task.resume()
}
}
| mit | 48f7ae79b21ae5c096d5a2a2a4d81afd | 27.615385 | 91 | 0.575269 | 4.694006 | false | false | false | false |
Czajnikowski/TrainTrippin | Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift | 3 | 10788 | //
// Observable+Creation.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
extension Observable {
// MARK: create
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func create(_ subscribe: @escaping (AnyObserver<E>) -> Disposable) -> Observable<E> {
return AnonymousObservable(subscribe)
}
// MARK: empty
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func empty() -> Observable<E> {
return Empty<E>()
}
// MARK: never
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func never() -> Observable<E> {
return Never()
}
// MARK: just
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func just(_ element: E) -> Observable<E> {
return Just(element: element)
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- parameter: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func just(_ element: E, scheduler: ImmediateSchedulerType) -> Observable<E> {
return JustScheduled(element: element, scheduler: scheduler)
}
// MARK: fail
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func error(_ error: Swift.Error) -> Observable<E> {
return Error(error: error)
}
// MARK: of
/**
This method creates a new Observable instance with a variable number of elements.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription.
- returns: The observable sequence whose elements are pulled from the given arguments.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func of(_ elements: E ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return ObservableSequence(elements: elements, scheduler: scheduler)
}
// MARK: defer
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func deferred(_ observableFactory: @escaping () throws -> Observable<E>)
-> Observable<E> {
return Deferred(observableFactory: observableFactory)
}
/**
Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler
to run the loop send out observer messages.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter initialState: Initial state.
- parameter condition: Condition to terminate generation (upon returning `false`).
- parameter iterate: Iteration step function.
- parameter scheduler: Scheduler on which to run the generator loop.
- returns: The generated sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func generate(initialState: E, condition: @escaping (E) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (E) throws -> E) -> Observable<E> {
return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler)
}
/**
Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages.
- seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html)
- parameter element: Element to repeat.
- parameter scheduler: Scheduler to run the producer loop on.
- returns: An observable sequence that repeats the given element infinitely.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func repeatElement(_ element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RepeatElement(element: element, scheduler: scheduler)
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html)
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func using<R: Disposable>(_ resourceFactory: @escaping () throws -> R, observableFactory: @escaping (R) throws -> Observable<E>) -> Observable<E> {
return Using(resourceFactory: resourceFactory, observableFactory: observableFactory)
}
}
extension Observable where Element : SignedInteger {
/**
Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages.
- seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html)
- parameter start: The value of the first integer in the sequence.
- parameter count: The number of sequential integers to generate.
- parameter scheduler: Scheduler to run the generator loop on.
- returns: An observable sequence that contains a range of sequential integral numbers.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public static func range(start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RangeProducer<E>(start: start, count: count, scheduler: scheduler)
}
}
extension Sequence {
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "Observable.from()")
public func toObservable(_ scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<Iterator.Element> {
return ObservableSequence(elements: Array(self), scheduler: scheduler)
}
}
extension Array {
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "Observable.from()")
public func toObservable(_ scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<Iterator.Element> {
return ObservableSequence(elements: self, scheduler: scheduler)
}
}
extension Observable {
/**
Converts an array to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from(_ array: [E], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return ObservableSequence(elements: array, scheduler: scheduler)
}
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from<S: Sequence>(_ sequence: S, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> where S.Iterator.Element == E {
return ObservableSequence(elements: sequence, scheduler: scheduler)
}
}
| mit | 81675cf990466e932c9fdd4cfd5e95cf | 43.028571 | 213 | 0.717623 | 4.702267 | false | false | false | false |
karupanerura/Reactift | Reactift/Observar.swift | 1 | 781 | //
// Observar.swift
// Reactift
//
// Created by karupanerura on 3/20/15.
// Copyright (c) 2015 karupanerura. All rights reserved.
//
import Foundation
public class Observar<T> {
typealias OnNextCallback = (T)->()
typealias OnCompleteCallback = ()->()
let onNext : OnNextCallback
let onComplete : OnCompleteCallback
private var suspendFg : Bool
init (onNext: OnNextCallback, onComplete: OnCompleteCallback) {
self.onNext = onNext
self.onComplete = onComplete
self.suspendFg = false
}
func suspend () -> Self {
self.suspendFg = true
return self
}
func resume () -> Self {
self.suspendFg = false
return self
}
func dispose () {
self.suspend()
}
}
| mit | a11d07077b5a03d7467be03e49f2431c | 20.108108 | 67 | 0.604353 | 3.964467 | false | false | false | false |
zyuanming/EffectDesignerX | EffectDesignerX/View/Helpers.swift | 1 | 2016 | //
// Helpers.swift
// KPCTabsControl
//
// Created by Cédric Foellmi on 03/09/16.
// Licensed under the MIT License (see LICENSE file)
//
import Foundation
/// Offset is a simple NSPoint typealias to increase readability.
public typealias Offset = NSPoint
public extension Offset {
public init(x: CGFloat) {
self.x = x
self.y = 0
}
public init(y: CGFloat) {
self.x = 0
self.y = y
}
}
/**
Addition operator for NSPoints and Offsets.
- parameter lhs: lef-hand side point
- parameter rhs: right-hand side offset to be added to the point.
- returns: A new and offset NSPoint.
*/
public func +(lhs: NSPoint, rhs: Offset) -> NSPoint {
return NSPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
/**
A convenience extension to easily shrink a NSRect
*/
public extension NSRect {
/// Change width and height by `-dx` and `-dy`.
func shrinkBy(dx: CGFloat, dy: CGFloat) -> NSRect {
var result = self
result.size = CGSize(width: result.size.width - dx, height: result.size.height - dy)
return result
}
}
/**
Convenience function to easily compare tab widths.
- parameter t1: The first tab width
- parameter t2: The second tab width
- returns: A boolean to indicate whether the tab widths are identical or not.
*/
func ==(t1: TabWidth, t2: TabWidth) -> Bool {
return String(describing: t1) == String(describing: t2)
}
/// Helper functions to let compare optionals
func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
| mit | bfa705437b3dcf0ebe5515edeaa06483 | 20.43617 | 92 | 0.597022 | 3.547535 | false | false | false | false |
paulofaria/SwiftHTTPServer | Example Server/Responders/JSONResponder.swift | 3 | 2117 | // JSONResponder.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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.
struct JSONResponder {
static func get(request: HTTPRequest) -> HTTPResponse {
let json: JSON = [
"null": nil,
"string": "Foo Bar",
"boolean": true,
"array": [
"1",
2,
nil,
true,
["1", 2, nil, false],
["a": "b"]
],
"object": [
"a": "1",
"b": 2,
"c": nil,
"d": false,
"e": ["1", 2, nil, false],
"f": ["a": "b"]
],
"number": 1969
]
return HTTPResponse(json: json)
}
static func post(request: HTTPRequest) throws -> HTTPResponse {
var json: JSON = try request.getData("JSON")
json["number"] = 321
json["array"][0] = 3
json["array"][2] = 1
return HTTPResponse(json: json)
}
}
| mit | a5d25809677146ed5f5461e86704f37b | 29.242857 | 81 | 0.576287 | 4.475687 | false | false | false | false |
FoxerLee/iOS_sitp | tiankeng/RegisterViewController.swift | 1 | 5053 | //
// RegisterViewController.swift
// tiankeng
//
// Created by 李源 on 2017/3/6.
// Copyright © 2017年 foxerlee. All rights reserved.
//
import UIKit
//import LeanCloud
import AVOSCloud
import os
class RegisterViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
@IBOutlet weak var confirmButton: UIButton!
@IBOutlet weak var iconImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
iconImageView.layer.masksToBounds = true
iconImageView.layer.cornerRadius = iconImageView.frame.size.width / 2
// Do any additional setup after loading the view.
iconImageView.layer.cornerRadius = 10.0
iconImageView.layer.borderWidth = 5.0
iconImageView.layer.borderColor = UIColor.white.cgColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Register(_ sender: UIButton) {
//let registerUser = LCUser()
let registerUser = AVUser()
let userNameText = nameTextField.text ?? ""
let passwordText = passwordTextField.text ?? ""
let phoneText = phoneTextField.text ?? ""
//确保要全部输入
if(!userNameText.isEmpty && !passwordText.isEmpty && !phoneText.isEmpty) {
//将用户的用户名和密码放入数据库
registerUser.username = userNameText
registerUser.password = passwordText
registerUser.mobilePhoneNumber = phoneText
let data = UIImagePNGRepresentation(iconImageView.image!)
let photo = AVFile.init(data: data!)
registerUser.setObject(photo, forKey: "icon")
registerUser.signUpInBackground({ (Bool, Error) in
if(Bool) {
//切换回登陆界面
let sb = UIStoryboard(name: "Main", bundle:nil)
let vc = sb.instantiateViewController(withIdentifier: "LVC") as! ViewController
self.present(vc, animated: true, completion: nil)
}
else {
let alert = UIAlertController(title: "用户名或手机号已经被注册", message: nil, preferredStyle: .alert)
let action = UIAlertAction(title: "请重新输入", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
})
}
//如果没有输入完
else{
let alert = UIAlertController(title: "输入信息不完整", message: nil, preferredStyle: .alert)
let action = UIAlertAction(title: "请确认输入完全", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
@IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .photoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set photoImageView to display the selected image.
iconImageView.image = selectedImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismiss(animated: true, completion: nil)
}
//cancel按钮
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | 252a20b840b0779210baf5d50c4beb06 | 35.626866 | 134 | 0.618174 | 5.496081 | false | false | false | false |
aryaxt/TextInputBar | TextInputBar/Source/TextInputAccessoryView.swift | 1 | 3026 | //
// TextInputAccessoryView.swift
// TextInputBar
//
// Created by Aryan Ghassemi on 8/16/15.
// Copyright © 2015 Aryan Ghassemi. All rights reserved.
//
// https://github.com/aryaxt/TextInputBar
//
// 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 protocol TextInputAccessoryViewDelegate {
func textInputAccessoryView(didChnageToFrame rect: CGRect)
}
class TextInputAccessoryView: UIView {
weak var delegate: TextInputAccessoryViewDelegate!
private var isObserving = false
private let keyPathsToObserve = ["frame", "center"]
private let myContext = UnsafeMutablePointer<()>()
// MARK: - Initialization -
override init(frame: CGRect) {
super.init(frame: frame)
userInteractionEnabled = false
backgroundColor = UIColor.clearColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
removeObserversIfNeeded()
}
// MARK: - UIView Methods -
override func layoutSubviews() {
super.layoutSubviews()
if let superview = superview {
delegate.textInputAccessoryView(didChnageToFrame: superview.frame)
}
}
override func willMoveToSuperview(newSuperview: UIView?) {
removeObserversIfNeeded()
for path in keyPathsToObserve {
newSuperview?.addObserver(self, forKeyPath: path, options: .New, context: myContext)
}
isObserving = true
super.willMoveToSuperview(newSuperview)
}
// MARK: - Private -
func removeObserversIfNeeded() {
if isObserving {
for path in keyPathsToObserve {
superview?.removeObserver(self, forKeyPath:path)
}
}
}
// MARK: - KBO -
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let keyPath = keyPath,
let superview = superview
where object === superview && keyPathsToObserve.contains(keyPath) {
delegate.textInputAccessoryView(didChnageToFrame: superview.frame)
}
}
}
| mit | 7af6982f33cab47b3b6bd8c6a64467f9 | 28.950495 | 154 | 0.738843 | 4.138167 | false | false | false | false |
manfengjun/KYMart | Section/Home/View/Search/KYHomeHeadView.swift | 1 | 1765 | //
// KYHomeHeadView.swift
// KYMart
//
// Created by Jun on 2017/6/4.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYHomeHeadView: UICollectionReusableView {
@IBOutlet weak var searchView: UIView!
@IBOutlet var contentView: UICollectionReusableView!
var images:[Ad]?{
didSet {
var urls:[String] = []
for model in images! {
if let url = model.ad_code {
urls.append(url)
}
}
sdcircleView.imageURLStringsGroup = urls
}
}
fileprivate lazy var sdcircleView : SDCycleScrollView = {
let sdcircleView = SDCycleScrollView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH*20/49), delegate: self, placeholderImage: UIImage(named: ""))
return sdcircleView!
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView = Bundle.main.loadNibNamed("KYHomeHeadView", owner: self, options: nil)?.first as! UICollectionReusableView
contentView.frame = self.bounds
addSubview(contentView)
awakeFromNib()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
func setupUI() {
sdcircleView.backgroundColor = UIColor.white
searchView.layer.masksToBounds = true
searchView.layer.cornerRadius = 5.0
searchView.layer.borderColor = UIColor.hexStringColor(hex: "#CCCCCC").cgColor
searchView.layer.borderWidth = 0.5
addSubview(sdcircleView)
}
}
extension KYHomeHeadView:SDCycleScrollViewDelegate{
}
| mit | c66d876fdf123f1092002ea128e90356 | 28.864407 | 174 | 0.625993 | 4.67374 | false | false | false | false |
vector-im/vector-ios | RiotSwiftUI/Modules/AnalyticsPrompt/Coordinator/AnalyticsPromptCoordinator.swift | 1 | 3140 | //
// Copyright 2021 New Vector Ltd
//
// 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 SwiftUI
struct AnalyticsPromptCoordinatorParameters {
/// The session to use if analytics are enabled.
let session: MXSession
}
final class AnalyticsPromptCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: AnalyticsPromptCoordinatorParameters
private let analyticsPromptHostingController: UIViewController
private var _analyticsPromptViewModel: Any? = nil
@available(iOS 14.0, *)
fileprivate var analyticsPromptViewModel: AnalyticsPromptViewModel {
return _analyticsPromptViewModel as! AnalyticsPromptViewModel
}
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var completion: (() -> Void)?
// MARK: - Setup
@available(iOS 14.0, *)
init(parameters: AnalyticsPromptCoordinatorParameters) {
self.parameters = parameters
let strings = AnalyticsPromptStrings()
let promptType: AnalyticsPromptType
if Analytics.shared.promptShouldDisplayUpgradeMessage {
promptType = .upgrade
} else {
promptType = .newUser
}
let viewModel = AnalyticsPromptViewModel(promptType: promptType, strings: strings, termsURL: BuildSettings.analyticsConfiguration.termsURL)
let view = AnalyticsPrompt(viewModel: viewModel.context)
_analyticsPromptViewModel = viewModel
analyticsPromptHostingController = VectorHostingController(rootView: view)
}
// MARK: - Public
func start() {
guard #available(iOS 14.0, *) else {
MXLog.debug("[AnalyticsPromptCoordinator] start: Invalid iOS version, returning.")
return
}
MXLog.debug("[AnalyticsPromptCoordinator] did start.")
analyticsPromptViewModel.completion = { [weak self] result in
MXLog.debug("[AnalyticsPromptCoordinator] AnalyticsPromptViewModel did complete with result: \(result).")
guard let self = self else { return }
switch result {
case .enable:
Analytics.shared.optIn(with: self.parameters.session)
self.completion?()
case .disable:
Analytics.shared.optOut()
self.completion?()
}
}
}
func toPresentable() -> UIViewController {
return self.analyticsPromptHostingController
}
}
| apache-2.0 | 50f78c63f5f5907e7bbdc42248e66c32 | 31.708333 | 147 | 0.651592 | 5.259631 | false | false | false | false |
lanjing99/RxSwiftDemo | 24-building-complete-rxswift-app/final/QuickTodo/QuickTodo/Services/TaskService.swift | 1 | 3714 | /*
* Copyright (c) 2016 Razeware LLC
*
* 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 RealmSwift
import RxSwift
import RxRealm
struct TaskService: TaskServiceType {
init() {
// create a few default tasks
do {
let realm = try Realm()
if realm.objects(TaskItem.self).count == 0 {
["Chapter 5: Filtering operators",
"Chapter 4: Observables and Subjects in practice",
"Chapter 3: Subjects",
"Chapter 2: Observables",
"Chapter 1: Hello, RxSwift"].forEach {
self.createTask(title: $0)
}
}
} catch _ {
}
}
fileprivate func withRealm<T>(_ operation: String, action: (Realm) throws -> T) -> T? {
do {
let realm = try Realm()
return try action(realm)
} catch let err {
print("Failed \(operation) realm with error: \(err)")
return nil
}
}
@discardableResult
func createTask(title: String) -> Observable<TaskItem> {
let result = withRealm("creating") { realm -> Observable<TaskItem> in
let task = TaskItem()
task.title = title
try realm.write {
task.uid = (realm.objects(TaskItem.self).max(ofProperty: "uid") ?? 0) + 1
realm.add(task)
}
return .just(task)
}
return result ?? .error(TaskServiceError.creationFailed)
}
@discardableResult
func delete(task: TaskItem) -> Observable<Void> {
let result = withRealm("deleting") { realm-> Observable<Void> in
try realm.write {
realm.delete(task)
}
return .empty()
}
return result ?? .error(TaskServiceError.deletionFailed(task))
}
@discardableResult
func update(task: TaskItem, title: String) -> Observable<TaskItem> {
let result = withRealm("updating title") { realm -> Observable<TaskItem> in
try realm.write {
task.title = title
}
return .just(task)
}
return result ?? .error(TaskServiceError.updateFailed(task))
}
@discardableResult
func toggle(task: TaskItem) -> Observable<TaskItem> {
let result = withRealm("toggling") { realm -> Observable<TaskItem> in
try realm.write {
if task.checked == nil {
task.checked = Date()
} else {
task.checked = nil
}
}
return .just(task)
}
return result ?? .error(TaskServiceError.toggleFailed(task))
}
func tasks() -> Observable<Results<TaskItem>> {
let result = withRealm("getting tasks") { realm -> Observable<Results<TaskItem>> in
let realm = try Realm()
let tasks = realm.objects(TaskItem.self)
return Observable.collection(from: tasks)
}
return result ?? .empty()
}
}
| mit | 064c25c1e74be49beb193d8f83238244 | 31.017241 | 89 | 0.65482 | 4.206116 | false | false | false | false |
KaiCode2/swift-corelibs-foundation | Foundation/NSIndexSet.swift | 1 | 24620 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/* Class for managing set of indexes. The set of valid indexes are 0 .. NSNotFound - 1; trying to use indexes outside this range is an error. NSIndexSet uses NSNotFound as a return value in cases where the queried index doesn't exist in the set; for instance, when you ask firstIndex and there are no indexes; or when you ask for indexGreaterThanIndex: on the last index, and so on.
The following code snippets can be used to enumerate over the indexes in an NSIndexSet:
// Forward
var currentIndex = set.firstIndex
while currentIndex != NSNotFound {
...
currentIndex = set.indexGreaterThanIndex(currentIndex)
}
// Backward
var currentIndex = set.lastIndex
while currentIndex != NSNotFound {
...
currentIndex = set.indexLessThanIndex(currentIndex)
}
To enumerate without doing a call per index, you can use the method getIndexes:maxCount:inIndexRange:.
*/
public class NSIndexSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
// all instance variables are private
internal var _ranges = [NSRange]()
internal var _count = 0
override public init() {
_count = 0
_ranges = []
}
public init(indexesInRange range: NSRange) {
_count = range.length
_ranges = _count == 0 ? [] : [range]
}
public init(indexSet: NSIndexSet) {
_ranges = indexSet._ranges
_count = indexSet.count
}
public override func copy() -> AnyObject {
return copyWithZone(nil)
}
public func copyWithZone(_ zone: NSZone) -> AnyObject { NSUnimplemented() }
public override func mutableCopy() -> AnyObject {
return mutableCopyWithZone(nil)
}
public func mutableCopyWithZone(_ zone: NSZone) -> AnyObject { NSUnimplemented() }
public static func supportsSecureCoding() -> Bool { return true }
public required init?(coder aDecoder: NSCoder) { NSUnimplemented() }
public func encodeWithCoder(_ aCoder: NSCoder) {
NSUnimplemented()
}
public convenience init(index value: Int) {
self.init(indexesInRange: NSMakeRange(value, 1))
}
public func isEqualToIndexSet(_ indexSet: NSIndexSet) -> Bool {
guard indexSet !== self else {
return true
}
let otherRanges = indexSet._ranges
if _ranges.count != otherRanges.count {
return false
}
for (r1, r2) in zip(_ranges, otherRanges) {
if r1.length != r2.length || r1.location != r2.location {
return false
}
}
return true
}
public var count: Int {
return _count
}
/* The following six methods will return NSNotFound if there is no index in the set satisfying the query.
*/
public var firstIndex: Int {
return _ranges.first?.location ?? NSNotFound
}
public var lastIndex: Int {
guard _ranges.count > 0 else {
return NSNotFound
}
return NSMaxRange(_ranges.last!) - 1
}
internal func _indexAndRangeAdjacentToOrContainingIndex(_ idx : Int) -> (Int, NSRange)? {
let count = _ranges.count
guard count > 0 else {
return nil
}
var min = 0
var max = count - 1
while min < max {
let rIdx = (min + max) / 2
let range = _ranges[rIdx]
if range.location > idx {
max = rIdx
} else if NSMaxRange(range) - 1 < idx {
min = rIdx + 1
} else {
return (rIdx, range)
}
}
return (min, _ranges[min])
}
internal func _indexOfRangeContainingIndex (_ idx : Int) -> Int? {
if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) {
return NSLocationInRange(idx, range) ? rIdx : nil
} else {
return nil
}
}
internal func _indexOfRangeBeforeOrContainingIndex(_ idx : Int) -> Int? {
if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) {
if range.location <= idx {
return rIdx
} else if rIdx > 0 {
return rIdx - 1
} else {
return nil
}
} else {
return nil
}
}
internal func _indexOfRangeAfterOrContainingIndex(_ idx : Int) -> Int? {
if let (rIdx, range) = _indexAndRangeAdjacentToOrContainingIndex(idx) {
if NSMaxRange(range) - 1 >= idx {
return rIdx
} else if rIdx + 1 < _ranges.count {
return rIdx + 1
} else {
return nil
}
} else {
return nil
}
}
internal func _indexClosestToIndex(_ idx: Int, equalAllowed : Bool, following: Bool) -> Int? {
guard _count > 0 else {
return nil
}
if following {
var result = idx
if !equalAllowed {
guard idx < NSNotFound else {
return nil
}
result += 1
}
if let rangeIndex = _indexOfRangeAfterOrContainingIndex(result) {
let range = _ranges[rangeIndex]
return NSLocationInRange(result, range) ? result : range.location
}
} else {
var result = idx
if !equalAllowed {
guard idx > 0 else {
return nil
}
result -= 1
}
if let rangeIndex = _indexOfRangeBeforeOrContainingIndex(result) {
let range = _ranges[rangeIndex]
return NSLocationInRange(result, range) ? result : (NSMaxRange(range) - 1)
}
}
return nil
}
public func indexGreaterThanIndex(_ value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: false, following: true) ?? NSNotFound
}
public func indexLessThanIndex(_ value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: false, following: false) ?? NSNotFound
}
public func indexGreaterThanOrEqualToIndex(_ value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: true, following: true) ?? NSNotFound
}
public func indexLessThanOrEqualToIndex(_ value: Int) -> Int {
return _indexClosestToIndex(value, equalAllowed: true, following: false) ?? NSNotFound
}
/* Fills up to bufferSize indexes in the specified range into the buffer and returns the number of indexes actually placed in the buffer; also modifies the optional range passed in by pointer to be "positioned" after the last index filled into the buffer.Example: if the index set contains the indexes 0, 2, 4, ..., 98, 100, for a buffer of size 10 and the range (20, 80) the buffer would contain 20, 22, ..., 38 and the range would be modified to (40, 60).
*/
public func getIndexes(_ indexBuffer: UnsafeMutablePointer<Int>, maxCount bufferSize: Int, inIndexRange range: NSRangePointer?) -> Int {
let minIndex : Int
let maxIndex : Int
if let initialRange = range {
minIndex = initialRange.pointee.location
maxIndex = NSMaxRange(initialRange.pointee) - 1
} else {
minIndex = firstIndex
maxIndex = lastIndex
}
guard minIndex <= maxIndex else {
return 0
}
if let initialRangeIndex = self._indexOfRangeAfterOrContainingIndex(minIndex) {
var rangeIndex = initialRangeIndex
let rangeCount = _ranges.count
var counter = 0
var idx = minIndex
var offset = 0
while rangeIndex < rangeCount && idx <= maxIndex && counter < bufferSize {
let currentRange = _ranges[rangeIndex]
if currentRange.location <= minIndex {
idx = minIndex
offset = minIndex - currentRange.location
} else {
idx = currentRange.location
}
while idx <= maxIndex && counter < bufferSize && offset < currentRange.length {
indexBuffer.advanced(by: counter).pointee = idx
counter += 1
idx += 1
offset += 1
}
if offset >= currentRange.length {
rangeIndex += 1
offset = 0
}
}
if counter > 0, let resultRange = range {
let delta = indexBuffer.advanced(by: counter - 1).pointee - minIndex + 1
resultRange.pointee.location += delta
resultRange.pointee.length -= delta
}
return counter
} else {
return 0
}
}
public func countOfIndexesInRange(_ range: NSRange) -> Int {
guard _count > 0 && range.length > 0 else {
return 0
}
if let initialRangeIndex = self._indexOfRangeAfterOrContainingIndex(range.location) {
var rangeIndex = initialRangeIndex
let maxRangeIndex = NSMaxRange(range) - 1
var result = 0
let firstRange = _ranges[rangeIndex]
if firstRange.location < range.location {
if NSMaxRange(firstRange) - 1 >= maxRangeIndex {
return range.length
}
result = NSMaxRange(firstRange) - range.location
rangeIndex += 1
}
for curRange in _ranges.suffix(from: rangeIndex) {
if NSMaxRange(curRange) - 1 > maxRangeIndex {
if curRange.location <= maxRangeIndex {
result += maxRangeIndex + 1 - curRange.location
}
break
}
result += curRange.length
}
return result
} else {
return 0
}
}
public func containsIndex(_ value: Int) -> Bool {
return _indexOfRangeContainingIndex(value) != nil
}
public func containsIndexesInRange(_ range: NSRange) -> Bool {
guard range.length > 0 else {
return false
}
if let rIdx = self._indexOfRangeContainingIndex(range.location) {
return NSMaxRange(_ranges[rIdx]) >= NSMaxRange(range)
} else {
return false
}
}
public func containsIndexes(_ indexSet: NSIndexSet) -> Bool {
guard self !== indexSet else {
return true
}
var result = true
enumerateRangesUsingBlock { range, stop in
if !self.containsIndexesInRange(range) {
result = false
stop.pointee = true
}
}
return result
}
public func intersectsIndexesInRange(_ range: NSRange) -> Bool {
guard range.length > 0 else {
return false
}
if let rIdx = _indexOfRangeBeforeOrContainingIndex(range.location) {
if NSMaxRange(_ranges[rIdx]) - 1 >= range.location {
return true
}
}
if let rIdx = _indexOfRangeAfterOrContainingIndex(range.location) {
if NSMaxRange(range) - 1 >= _ranges[rIdx].location {
return true
}
}
return false
}
internal func _enumerateWithOptions<P, R>(_ opts : NSEnumerationOptions, range: NSRange, paramType: P.Type, returnType: R.Type, block: (P, UnsafeMutablePointer<ObjCBool>) -> R) -> Int? {
guard !opts.contains(.concurrent) else {
NSUnimplemented()
}
guard let startRangeIndex = self._indexOfRangeAfterOrContainingIndex(range.location), let endRangeIndex = _indexOfRangeBeforeOrContainingIndex(NSMaxRange(range) - 1) else {
return nil
}
var result : Int? = nil
let reverse = opts.contains(.reverse)
let passRanges = paramType == NSRange.self
let findIndex = returnType == Bool.self
var stop = false
let ranges = _ranges[startRangeIndex...endRangeIndex]
let rangeSequence = (reverse ? AnySequence(ranges.reversed()) : AnySequence(ranges))
outer: for curRange in rangeSequence {
let intersection = NSIntersectionRange(curRange, range)
if passRanges {
if intersection.length > 0 {
block(intersection as! P, &stop)
}
if stop {
break outer
}
} else if intersection.length > 0 {
let maxIndex = NSMaxRange(intersection) - 1
let indexes = reverse ? stride(from: maxIndex, through: intersection.location, by: -1) : stride(from: intersection.location, through: maxIndex, by: 1)
for idx in indexes {
if findIndex {
let found : Bool = block(idx as! P, &stop) as! Bool
if found {
result = idx
stop = true
}
} else {
block(idx as! P, &stop)
}
if stop {
break outer
}
}
} // else, continue
}
return result
}
public func enumerateIndexesUsingBlock(_ block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateIndexesWithOptions([], usingBlock: block)
}
public func enumerateIndexesWithOptions(_ opts: NSEnumerationOptions, usingBlock block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) {
let _ = _enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: Int.self, returnType: Void.self, block: block)
}
public func enumerateIndexesInRange(_ range: NSRange, options opts: NSEnumerationOptions, usingBlock block: (Int, UnsafeMutablePointer<ObjCBool>) -> Void) {
let _ = _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Void.self, block: block)
}
public func indexPassingTest(_ predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return indexWithOptions([], passingTest: predicate)
}
public func indexWithOptions(_ opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return _enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: Int.self, returnType: Bool.self, block: predicate) ?? NSNotFound
}
public func indexInRange(_ range: NSRange, options opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Int {
return _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Bool.self, block: predicate) ?? NSNotFound
}
public func indexesPassingTest(_ predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet {
return indexesInRange(NSMakeRange(0, Int.max), options: [], passingTest: predicate)
}
public func indexesWithOptions(_ opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet {
return indexesInRange(NSMakeRange(0, Int.max), options: opts, passingTest: predicate)
}
public func indexesInRange(_ range: NSRange, options opts: NSEnumerationOptions, passingTest predicate: (Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> NSIndexSet {
let result = NSMutableIndexSet()
let _ = _enumerateWithOptions(opts, range: range, paramType: Int.self, returnType: Void.self) { idx, stop in
if predicate(idx, stop) {
result.addIndex(idx)
}
}
return result
}
/*
The following three convenience methods allow you to enumerate the indexes in the receiver by ranges of contiguous indexes. The performance of these methods is not guaranteed to be any better than if they were implemented with enumerateIndexesInRange:options:usingBlock:. However, depending on the receiver's implementation, they may perform better than that.
If the specified range for enumeration intersects a range of contiguous indexes in the receiver, then the block will be invoked with the intersection of those two ranges.
*/
public func enumerateRangesUsingBlock(_ block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateRangesWithOptions([], usingBlock: block)
}
public func enumerateRangesWithOptions(_ opts: NSEnumerationOptions, usingBlock block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
let _ = _enumerateWithOptions(opts, range: NSMakeRange(0, Int.max), paramType: NSRange.self, returnType: Void.self, block: block)
}
public func enumerateRangesInRange(_ range: NSRange, options opts: NSEnumerationOptions, usingBlock block: (NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
let _ = _enumerateWithOptions(opts, range: range, paramType: NSRange.self, returnType: Void.self, block: block)
}
}
extension NSIndexSet : Sequence {
public struct Iterator : IteratorProtocol {
internal let _set: NSIndexSet
internal var _first: Bool = true
internal var _current: Int?
internal init(_ set: NSIndexSet) {
self._set = set
self._current = nil
}
public mutating func next() -> Int? {
if _first {
_current = _set.firstIndex
_first = false
} else if let c = _current {
_current = _set.indexGreaterThanIndex(c)
}
if _current == NSNotFound {
_current = nil
}
return _current
}
}
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
public class NSMutableIndexSet : NSIndexSet {
public func addIndexes(_ indexSet: NSIndexSet) {
indexSet.enumerateRangesUsingBlock { range, _ in
self.addIndexesInRange(range)
}
}
public func removeIndexes(_ indexSet: NSIndexSet) {
indexSet.enumerateRangesUsingBlock { range, _ in
self.removeIndexesInRange(range)
}
}
public func removeAllIndexes() {
_ranges = []
_count = 0
}
public func addIndex(_ value: Int) {
self.addIndexesInRange(NSMakeRange(value, 1))
}
public func removeIndex(_ value: Int) {
self.removeIndexesInRange(NSMakeRange(value, 1))
}
internal func _insertRange(_ range: NSRange, atIndex index: Int) {
_ranges.insert(range, at: index)
_count += range.length
}
internal func _replaceRangeAtIndex(_ index: Int, withRange range: NSRange?) {
let oldRange = _ranges[index]
if let range = range {
_ranges[index] = range
_count += range.length - oldRange.length
} else {
_ranges.remove(at: index)
_count -= oldRange.length
}
}
internal func _mergeOverlappingRangesStartingAtIndex(_ index: Int) {
var rangeIndex = index
while _ranges.count > 0 && rangeIndex < _ranges.count - 1 {
let curRange = _ranges[rangeIndex]
let nextRange = _ranges[rangeIndex + 1]
let curEnd = NSMaxRange(curRange)
let nextEnd = NSMaxRange(nextRange)
if curEnd >= nextRange.location {
// overlaps
if curEnd < nextEnd {
self._replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(nextEnd - curRange.location, curRange.length))
rangeIndex += 1
}
self._replaceRangeAtIndex(rangeIndex + 1, withRange: nil)
} else {
break
}
}
}
public func addIndexesInRange(_ range: NSRange) {
guard range.length > 0 else {
return
}
let addEnd = NSMaxRange(range)
let startRangeIndex = _indexOfRangeBeforeOrContainingIndex(range.location) ?? 0
var replacedRangeIndex : Int?
var rangeIndex = startRangeIndex
while rangeIndex < _ranges.count {
let curRange = _ranges[rangeIndex]
let curEnd = NSMaxRange(curRange)
if addEnd < curRange.location {
_insertRange(range, atIndex: rangeIndex)
// Done. No need to merge
return
} else if range.location < curRange.location && addEnd >= curRange.location {
if addEnd > curEnd {
_replaceRangeAtIndex(rangeIndex, withRange: range)
} else {
_replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(range.location, curEnd - range.location))
}
replacedRangeIndex = rangeIndex
// Proceed to merging
break
} else if range.location >= curRange.location && addEnd < curEnd {
// Nothing to add
return
} else if range.location >= curRange.location && range.location <= curEnd && addEnd > curEnd {
_replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(curRange.location, addEnd - curRange.location))
replacedRangeIndex = rangeIndex
// Proceed to merging
break
}
rangeIndex += 1
}
if let r = replacedRangeIndex {
_mergeOverlappingRangesStartingAtIndex(r)
} else {
_insertRange(range, atIndex: _ranges.count)
}
}
public func removeIndexesInRange(_ range: NSRange) {
guard range.length > 0 else {
return
}
guard let startRangeIndex = (range.location > 0) ? _indexOfRangeAfterOrContainingIndex(range.location) : 0 else {
return
}
let removeEnd = NSMaxRange(range)
var rangeIndex = startRangeIndex
while rangeIndex < _ranges.count {
let curRange = _ranges[rangeIndex]
let curEnd = NSMaxRange(curRange)
if removeEnd < curRange.location {
// Nothing to remove
return
} else if range.location <= curRange.location && removeEnd >= curRange.location {
if removeEnd >= curEnd {
_replaceRangeAtIndex(rangeIndex, withRange: nil)
// Don't increment rangeIndex
continue
} else {
self._replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(removeEnd, curEnd - removeEnd))
return
}
} else if range.location > curRange.location && removeEnd < curEnd {
let firstPiece = NSMakeRange(curRange.location, range.location - curRange.location)
let secondPiece = NSMakeRange(removeEnd, curEnd - removeEnd)
_replaceRangeAtIndex(rangeIndex, withRange: secondPiece)
_insertRange(firstPiece, atIndex: rangeIndex)
} else if range.location > curRange.location && range.location < curEnd && removeEnd >= curEnd {
_replaceRangeAtIndex(rangeIndex, withRange: NSMakeRange(curRange.location, range.location - curRange.location))
}
rangeIndex += 1
}
}
/* For a positive delta, shifts the indexes in [index, INT_MAX] to the right, thereby inserting an "empty space" [index, delta], for a negative delta, shifts the indexes in [index, INT_MAX] to the left, thereby deleting the indexes in the range [index - delta, delta].
*/
public func shiftIndexesStartingAtIndex(_ index: Int, by delta: Int) { NSUnimplemented() }
}
| apache-2.0 | 74296cba85981203fc815238e873e893 | 38.518459 | 461 | 0.574086 | 5.353338 | false | false | false | false |
phimage/Prephirences | Sources/PrephirenceType+Codable.swift | 1 | 998 | //
// PrephirenceType+Codable.swift
// Prephirences
//
// Created by Eric Marchand on 25/05/2018.
// Copyright © 2018 phimage. All rights reserved.
//
import Foundation
extension Prephirences {
public static var jsonDecoder = JSONDecoder()
public static var jsonEncoder = JSONEncoder()
}
extension PreferencesType {
public func decodable<T: Decodable>(_ type: T.Type, forKey key: PreferenceKey, decoder: JSONDecoder = Prephirences.jsonDecoder) throws -> T? {
guard let data = data(forKey: key) else {
return nil
}
return try decoder.decode(T.self, from: data)
}
}
extension MutablePreferencesType {
public func set<T: Encodable>(encodable value: T?, forKey key: PreferenceKey, encoder: JSONEncoder = Prephirences.jsonEncoder) throws {
if let value = value {
let data: Data = try encoder.encode(value)
set(data, forKey: key)
} else {
removeObject(forKey: key)
}
}
}
| mit | 73201801cbc6080efc9abc32c1c3d404 | 25.236842 | 146 | 0.650953 | 4.27897 | false | false | false | false |
eljeff/AudioKit | Sources/AudioKit/Operations/Generators/Physical Models/vocalTractOperation.swift | 2 | 1125 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
extension Operation {
/// Karplus-Strong plucked string instrument.
///
/// - Parameters:
/// - frequency: Glottal frequency.
/// - tonguePosition: Tongue position (0-1)
/// - tongueDiameter: Tongue diameter (0-1)
/// - tenseness: Vocal tenseness. 0 = all breath. 1=fully saturated.
/// - nasality: Sets the velum size. Larger values of this creates more nasally sounds.
///
/// NOTE: This node is CPU intensitve and will drop packet if your buffer size is
/// too short. It requires at least 64 samples on an iPhone X, for example.
public static func vocalTract(
frequency: OperationParameter = 160.0,
tonguePosition: OperationParameter = 0.5,
tongueDiameter: OperationParameter = 1.0,
tenseness: OperationParameter = 0.6,
nasality: OperationParameter = 0.0) -> Operation {
return Operation(module: "voc",
inputs: frequency, tonguePosition, tongueDiameter, tenseness, nasality)
}
}
| mit | af3411ad7a5146903ec513aa8966974a | 42.269231 | 100 | 0.653333 | 4.182156 | false | false | false | false |
uber/rides-ios-sdk | source/UberCore/Deeplinks/RidesAppStoreDeeplink.swift | 1 | 2163 | //
// RidesAppStoreDeeplink.swift
// UberRides
//
// Copyright © 2016 Uber Technologies, Inc. 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
/**
* A Deeplinking object for opening the App Store to the native Uber rides app.
*/
@objc(UBSDKRidesAppStoreDeeplink) public class RidesAppStoreDeeplink: BaseDeeplink {
/**
Initializes an App Store Deeplink to bring the user to the appstore
- returns: An initialized AppStoreDeeplink
*/
@objc public init(userAgent: String?) {
let scheme = "https"
let domain = "m.uber.com"
let path = "/sign-up"
let clientIDQueryItem = URLQueryItem(name: "client_id", value: Configuration.shared.clientID)
let userAgent = userAgent ?? "rides-ios-v\(Configuration.shared.sdkVersion)"
let userAgentQueryItem = URLQueryItem(name: "user-agent", value: userAgent)
let queryItems = [clientIDQueryItem, userAgentQueryItem]
super.init(scheme: scheme, host: domain, path: path, queryItems: queryItems)!
}
}
| mit | e73582db23bcfcb3501c2e1ab563bc5f | 40.576923 | 101 | 0.707216 | 4.523013 | false | false | false | false |
natecook1000/swift | test/Constraints/tuple_arguments.swift | 2 | 53129 | // RUN: %target-typecheck-verify-swift -swift-version 5
// See test/Compatibility/tuple_arguments_3.swift for the Swift 3 behavior.
// See test/Compatibility/tuple_arguments_4.swift for the Swift 4 behavior.
func concrete(_ x: Int) {}
func concreteLabeled(x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
do {
concrete(3)
concrete((3))
concreteLabeled(x: 3)
concreteLabeled(x: (3))
concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}}
concreteTwo(3, 4)
concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
concreteTuple(3, 4) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((a, b))
concreteTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((a, b))
concreteTuple(d)
}
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
do {
generic(3)
generic(3, 4) // expected-error {{extra argument in call}}
generic((3))
generic((3, 4))
genericLabeled(x: 3)
genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
genericLabeled(x: (3))
genericLabeled(x: (3, 4))
genericTwo(3, 4)
genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(3, 4) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}}
genericTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
generic(a)
generic(a, b) // expected-error {{extra argument in call}}
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}}
genericTuple((a, b))
genericTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
generic(a)
generic(a, b) // expected-error {{extra argument in call}}
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)'}} {{16-16=(}} {{20-20=)}}
genericTuple((a, b))
genericTuple(d)
}
var function: (Int) -> ()
var functionTwo: (Int, Int) -> () // expected-note 5 {{'functionTwo' declared here}}
var functionTuple: ((Int, Int)) -> ()
do {
function(3)
function((3))
functionTwo(3, 4)
functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
functionTuple(3, 4) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((a, b))
functionTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((a, b))
functionTuple(d)
}
struct Concrete {}
extension Concrete {
func concrete(_ x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
}
do {
let s = Concrete()
s.concrete(3)
s.concrete((3))
s.concreteTwo(3, 4)
s.concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTuple(3, 4) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((a, b))
s.concreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((a, b))
s.concreteTuple(d)
}
extension Concrete {
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
}
do {
let s = Concrete()
s.generic(3)
s.generic(3, 4) // expected-error {{extra argument in call}}
s.generic((3))
s.generic((3, 4))
s.genericLabeled(x: 3)
s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.genericLabeled(x: (3))
s.genericLabeled(x: (3, 4))
s.genericTwo(3, 4)
s.genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(3, 4) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.generic(a)
s.generic(a, b) // expected-error {{extra argument in call}}
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
s.genericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.generic(a)
s.generic(a, b) // expected-error {{extra argument in call}}
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
s.genericTuple(d)
}
extension Concrete {
mutating func mutatingConcrete(_ x: Int) {}
mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'mutatingConcreteTwo' declared here}}
mutating func mutatingConcreteTuple(_ x: (Int, Int)) {}
}
do {
var s = Concrete()
s.mutatingConcrete(3)
s.mutatingConcrete((3))
s.mutatingConcreteTwo(3, 4)
s.mutatingConcreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTuple(3, 4) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
extension Concrete {
mutating func mutatingGeneric<T>(_ x: T) {}
mutating func mutatingGenericLabeled<T>(x: T) {}
mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {}
}
do {
var s = Concrete()
s.mutatingGeneric(3)
s.mutatingGeneric(3, 4) // expected-error {{extra argument in call}}
s.mutatingGeneric((3))
s.mutatingGeneric((3, 4))
s.mutatingGenericLabeled(x: 3)
s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.mutatingGenericLabeled(x: (3))
s.mutatingGenericLabeled(x: (3, 4))
s.mutatingGenericTwo(3, 4)
s.mutatingGenericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(3, 4) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric(a, b) // expected-error {{extra argument in call}}
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric(a, b) // expected-error {{extra argument in call}}
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
extension Concrete {
var function: (Int) -> () { return concrete }
var functionTwo: (Int, Int) -> () { return concreteTwo }
var functionTuple: ((Int, Int)) -> () { return concreteTuple }
}
do {
let s = Concrete()
s.function(3)
s.function((3))
s.functionTwo(3, 4)
s.functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.functionTuple(3, 4) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}}
s.functionTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.functionTuple(a, b) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}}
s.functionTuple((a, b))
s.functionTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.functionTuple(a, b) // expected-error {{single parameter of type '(Int, Int)' is expected in call}} {{19-19=(}} {{23-23=)}}
s.functionTuple((a, b))
s.functionTuple(d)
}
struct InitTwo {
init(_ x: Int, _ y: Int) {} // expected-note 5 {{'init' declared here}}
}
struct InitTuple {
init(_ x: (Int, Int)) {}
}
struct InitLabeledTuple {
init(x: (Int, Int)) {}
}
do {
_ = InitTwo(3, 4)
_ = InitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((3, 4))
_ = InitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = InitLabeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((a, b))
_ = InitTuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((a, b))
_ = InitTuple(c)
}
struct SubscriptTwo {
subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript' declared here}}
}
struct SubscriptTuple {
subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } }
}
struct SubscriptLabeledTuple {
subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } }
}
do {
let s1 = SubscriptTwo()
_ = s1[3, 4]
_ = s1[(3, 4)] // expected-error {{missing argument for parameter #2 in call}}
let s2 = SubscriptTuple()
_ = s2[3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(3, 4)]
}
do {
let a = 3
let b = 4
let d = (a, b)
let s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s1[d] // expected-error {{missing argument for parameter #2 in call}}
let s2 = SubscriptTuple()
_ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(a, b)]
_ = s2[d]
let s3 = SubscriptLabeledTuple()
_ = s3[x: 3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}}
_ = s3[x: (3, 4)]
}
do {
// TODO: Restore regressed diagnostics rdar://problem/31724211
var a = 3 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
var s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s1[d] // expected-error {{missing argument for parameter #2 in call}}
var s2 = SubscriptTuple()
_ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(a, b)]
_ = s2[d]
}
enum Enum {
case two(Int, Int) // expected-note 6 {{'two' declared here}}
case tuple((Int, Int))
case labeledTuple(x: (Int, Int))
}
do {
_ = Enum.two(3, 4)
_ = Enum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.two(3 > 4 ? 3 : 4) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((3, 4))
_ = Enum.labeledTuple(x: 3, 4) // expected-error {{enum case 'labeledTuple' expects a single parameter of type '(Int, Int)'}}
_ = Enum.labeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
struct Generic<T> {}
extension Generic {
func generic(_ x: T) {}
func genericLabeled(x: T) {}
func genericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'genericTwo' declared here}}
func genericTuple(_ x: (T, T)) {}
}
do {
let s = Generic<Double>()
s.generic(3.0)
s.generic((3.0))
s.genericLabeled(x: 3.0)
s.genericLabeled(x: (3.0))
s.genericTwo(3.0, 4.0)
s.genericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(3.0, 4.0) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{26-26=)}}
s.genericTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(3.0, 4.0) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{24-24=)}}
sTwo.generic((3.0, 4.0))
sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'genericLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.genericLabeled(x: (3.0, 4.0))
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}}
sTwo.generic((a, b))
sTwo.generic(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}}
sTwo.generic((a, b))
sTwo.generic(d)
}
extension Generic {
mutating func mutatingGeneric(_ x: T) {}
mutating func mutatingGenericLabeled(x: T) {}
mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple(_ x: (T, T)) {}
}
do {
var s = Generic<Double>()
s.mutatingGeneric(3.0)
s.mutatingGeneric((3.0))
s.mutatingGenericLabeled(x: 3.0)
s.mutatingGenericLabeled(x: (3.0))
s.mutatingGenericTwo(3.0, 4.0)
s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(3.0, 4.0) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}}
s.mutatingGenericTuple((3.0, 4.0))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}}
sTwo.mutatingGeneric((3.0, 4.0))
sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'mutatingGenericLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.mutatingGenericLabeled(x: (3.0, 4.0))
}
do {
var s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
extension Generic {
var genericFunction: (T) -> () { return generic }
var genericFunctionTwo: (T, T) -> () { return genericTwo }
var genericFunctionTuple: ((T, T)) -> () { return genericTuple }
}
do {
let s = Generic<Double>()
s.genericFunction(3.0)
s.genericFunction((3.0))
s.genericFunctionTwo(3.0, 4.0)
s.genericFunctionTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.genericFunctionTuple(3.0, 4.0) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{34-34=)}}
s.genericFunctionTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(3.0, 4.0) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{24-24=(}} {{32-32=)}}
sTwo.genericFunction((3.0, 4.0))
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericFunctionTuple(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{30-30=)}}
s.genericFunctionTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{24-24=(}} {{28-28=)}}
sTwo.genericFunction((a, b))
sTwo.genericFunction(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericFunctionTuple(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{26-26=(}} {{30-30=)}}
s.genericFunctionTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b) // expected-error {{single parameter of type '(Double, Double)' is expected in call}} {{24-24=(}} {{28-28=)}}
sTwo.genericFunction((a, b))
sTwo.genericFunction(d)
}
struct GenericInit<T> {
init(_ x: T) {}
}
struct GenericInitLabeled<T> {
init(x: T) {}
}
struct GenericInitTwo<T> {
init(_ x: T, _ y: T) {} // expected-note 10 {{'init' declared here}}
}
struct GenericInitTuple<T> {
init(_ x: (T, T)) {}
}
struct GenericInitLabeledTuple<T> {
init(x: (T, T)) {}
}
do {
_ = GenericInit(3, 4) // expected-error {{extra argument in call}}
_ = GenericInit((3, 4))
_ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeled(x: (3, 4))
_ = GenericInitTwo(3, 4)
_ = GenericInitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((3, 4))
_ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}}
_ = GenericInitLabeledTuple(x: (3, 4))
}
do {
_ = GenericInit<(Int, Int)>(3, 4) // expected-error {{extra argument in call}}
_ = GenericInit<(Int, Int)>((3, 4))
_ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeled<(Int, Int)>(x: (3, 4))
_ = GenericInitTwo<Int>(3, 4)
_ = GenericInitTwo<Int>((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple<Int>(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((3, 4))
_ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)'}}
_ = GenericInitLabeledTuple<Int>(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit(a, b) // expected-error {{extra argument in call}}
_ = GenericInit((a, b))
_ = GenericInit(c)
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit<(Int, Int)>(a, b) // expected-error {{extra argument in call}}
_ = GenericInit<(Int, Int)>((a, b))
_ = GenericInit<(Int, Int)>(c)
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo<Int>(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericInit(a, b) // expected-error {{extra argument in call}}
_ = GenericInit((a, b))
_ = GenericInit(c)
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericInit<(Int, Int)>(a, b) // expected-error {{extra argument in call}}
_ = GenericInit<(Int, Int)>((a, b))
_ = GenericInit<(Int, Int)>(c)
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo<Int>(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
struct GenericSubscript<T> {
subscript(_ x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptLabeled<T> {
subscript(x x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptTwo<T> {
subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript' declared here}}
}
struct GenericSubscriptLabeledTuple<T> {
subscript(x x: (T, T)) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptTuple<T> {
subscript(_ x: (T, T)) -> Int { get { return 0 } set { } }
}
do {
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[3.0, 4.0] // expected-error {{extra argument in call}}
_ = s1[(3.0, 4.0)]
let s1a = GenericSubscriptLabeled<(Double, Double)>()
_ = s1a [x: 3.0, 4.0] // expected-error {{extra argument in call}}
_ = s1a [x: (3.0, 4.0)]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[3.0, 4.0]
_ = s2[(3.0, 4.0)] // expected-error {{missing argument for parameter #2 in call}}
let s3 = GenericSubscriptTuple<Double>()
_ = s3[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{18-18=)}}
_ = s3[(3.0, 4.0)]
let s3a = GenericSubscriptLabeledTuple<Double>()
_ = s3a[x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(T, T)'}}
_ = s3a[x: (3.0, 4.0)]
}
do {
let a = 3.0
let b = 4.0
let d = (a, b)
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b] // expected-error {{extra argument in call}}
_ = s1[(a, b)]
_ = s1[d]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s2[d] // expected-error {{missing argument for parameter #2 in call}}
let s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{14-14=)}}
_ = s3[(a, b)]
_ = s3[d]
}
do {
// TODO: Restore regressed diagnostics rdar://problem/31724211
var a = 3.0 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4.0 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
var s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b] // expected-error {{extra argument in call}}
_ = s1[(a, b)]
_ = s1[d]
var s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s2[d] // expected-error {{missing argument for parameter #2 in call}}
var s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(T, T)'}} {{10-10=(}} {{14-14=)}}
_ = s3[(a, b)]
_ = s3[d]
}
enum GenericEnum<T> {
case one(T)
case labeled(x: T)
case two(T, T) // expected-note 10 {{'two' declared here}}
case tuple((T, T))
}
do {
_ = GenericEnum.one(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.one((3, 4))
_ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled(x: (3, 4))
_ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum.two(3, 4)
_ = GenericEnum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((3, 4))
}
do {
_ = GenericEnum<(Int, Int)>.one(3, 4) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((3, 4))
_ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}}
_ = GenericEnum<(Int, Int)>.labeled(x: (3, 4))
_ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}}
_ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum<Int>.two(3, 4)
_ = GenericEnum<Int>.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum.one(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum.one((a, b))
_ = GenericEnum.one(c)
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((a, b))
_ = GenericEnum<(Int, Int)>.one(c)
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericEnum.one(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum.one((a, b))
_ = GenericEnum.one(c)
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)'}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((a, b))
_ = GenericEnum<(Int, Int)>.one(c)
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
protocol Protocol {
associatedtype Element
}
extension Protocol {
func requirement(_ x: Element) {}
func requirementLabeled(x: Element) {}
func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 3 {{'requirementTwo' declared here}}
func requirementTuple(_ x: (Element, Element)) {}
}
struct GenericConforms<T> : Protocol {
typealias Element = T
}
do {
let s = GenericConforms<Double>()
s.requirement(3.0)
s.requirement((3.0))
s.requirementLabeled(x: 3.0)
s.requirementLabeled(x: (3.0))
s.requirementTwo(3.0, 4.0)
s.requirementTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.requirementTuple(3.0, 4.0) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{30-30=)}}
s.requirementTuple((3.0, 4.0))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(3.0, 4.0) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{28-28=)}}
sTwo.requirement((3.0, 4.0))
sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{instance method 'requirementLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.requirementLabeled(x: (3.0, 4.0))
}
do {
let s = GenericConforms<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{26-26=)}}
s.requirementTuple((a, b))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{24-24=)}}
sTwo.requirement((a, b))
sTwo.requirement(d)
}
do {
var s = GenericConforms<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(Double, Double)'}} {{22-22=(}} {{26-26=)}}
s.requirementTuple((a, b))
var sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type '(Double, Double)'}} {{20-20=(}} {{24-24=)}}
sTwo.requirement((a, b))
sTwo.requirement(d)
}
extension Protocol {
func takesClosure(_ fn: (Element) -> ()) {}
func takesClosureTwo(_ fn: (Element, Element) -> ()) {}
func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {}
}
do {
let s = GenericConforms<Double>()
s.takesClosure({ _ = $0 })
s.takesClosure({ x in })
s.takesClosure({ (x: Double) in })
s.takesClosureTwo({ _ = $0 }) // expected-error {{contextual closure type '(Double, Double) -> ()' expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ x in }) // expected-error {{contextual closure type '(Double, Double) -> ()' expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ (x: (Double, Double)) in }) // expected-error {{contextual closure type '(Double, Double) -> ()' expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ _ = $0; _ = $1 })
s.takesClosureTwo({ (x, y) in })
s.takesClosureTwo({ (x: Double, y:Double) in })
s.takesClosureTuple({ _ = $0 })
s.takesClosureTuple({ x in })
s.takesClosureTuple({ (x: (Double, Double)) in })
s.takesClosureTuple({ _ = $0; _ = $1 })
s.takesClosureTuple({ (x, y) in })
s.takesClosureTuple({ (x: Double, y:Double) in })
let sTwo = GenericConforms<(Double, Double)>()
sTwo.takesClosure({ _ = $0 })
sTwo.takesClosure({ x in })
sTwo.takesClosure({ (x: (Double, Double)) in })
sTwo.takesClosure({ _ = $0; _ = $1 })
sTwo.takesClosure({ (x, y) in })
sTwo.takesClosure({ (x: Double, y: Double) in })
}
do {
let _: ((Int, Int)) -> () = { _ = $0 }
let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) }
let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) }
let _: ((Int, Int)) -> () = { _ = ($0, $1) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}}
let _: ((Int, Int)) -> () = { t, u in _ = (t, u) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}} {{33-37=(arg)}} {{41-41=let (t, u) = arg; }}
let _: (Int, Int) -> () = { _ = $0 } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { _ = ($0.0, $0.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { t in _ = (t.0, t.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { _ = ($0, $1) }
let _: (Int, Int) -> () = { t, u in _ = (t, u) }
}
// rdar://problem/28952837 - argument labels ignored when calling function
// with single 'Any' parameter
func takesAny(_: Any) {}
enum HasAnyCase {
case any(_: Any)
}
do {
let fn: (Any) -> () = { _ in }
fn(123)
fn(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
takesAny(123)
takesAny(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
_ = HasAnyCase.any(123)
_ = HasAnyCase.any(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
}
// rdar://problem/29739905 - protocol extension methods on Array had
// ParenType sugar stripped off the element type
func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()],
f2: [(Bool, Bool) -> ()],
c: Bool) {
let p = (c, c)
f1.forEach { block in
block(p)
block((c, c))
block(c, c) // expected-error {{parameter 'block' expects a single parameter of type '(Bool, Bool)'}} {{11-11=(}} {{15-15=)}}
}
f2.forEach { block in
// expected-note@-1 2{{'block' declared here}}
block(p) // expected-error {{missing argument for parameter #2 in call}}
block((c, c)) // expected-error {{missing argument for parameter #2 in call}}
block(c, c)
}
f2.forEach { (block: ((Bool, Bool)) -> ()) in
// expected-error@-1 {{cannot convert value of type '(((Bool, Bool)) -> ()) -> ()' to expected argument type '((Bool, Bool) -> ()) -> Void}}
block(p)
block((c, c))
block(c, c)
}
f2.forEach { (block: (Bool, Bool) -> ()) in
// expected-note@-1 2{{'block' declared here}}
block(p) // expected-error {{missing argument for parameter #2 in call}}
block((c, c)) // expected-error {{missing argument for parameter #2 in call}}
block(c, c)
}
}
// expected-error@+1 {{cannot create a single-element tuple with an element label}}
func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) {
// TODO: Error could be improved.
// expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}}
completion((didAdjust: true))
}
// SR-4378
final public class MutableProperty<Value> {
public init(_ initialValue: Value) {}
}
enum DataSourcePage<T> {
case notLoaded
}
let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: .notLoaded,
totalCount: 0
))
let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: DataSourcePage.notLoaded,
totalCount: 0
))
let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: DataSourcePage<Int>.notLoaded,
totalCount: 0
))
// SR-4745
let sr4745 = [1, 2]
let _ = sr4745.enumerated().map { (count, element) in "\(count): \(element)" }
// SR-4738
let sr4738 = (1, (2, 3))
[sr4738].map { (x, (y, z)) -> Int in x + y + z } // expected-error {{use of undeclared type 'y'}}
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{20-26=arg1}} {{38-38=let (y, z) = arg1; }}
// rdar://problem/31892961
let r31892961_1 = [1: 1, 2: 2]
r31892961_1.forEach { (k, v) in print(k + v) }
let r31892961_2 = [1, 2, 3]
let _: [Int] = r31892961_2.enumerated().map { ((index, val)) in
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{48-60=arg0}} {{3-3=\n let (index, val) = arg0\n }}
// expected-error@-2 {{use of undeclared type 'index'}}
val + 1
}
let r31892961_3 = (x: 1, y: 42)
_ = [r31892961_3].map { (x: Int, y: Int) in x + y }
_ = [r31892961_3].map { (x, y: Int) in x + y }
let r31892961_4 = (1, 2)
_ = [r31892961_4].map { x, y in x + y }
let r31892961_5 = (x: 1, (y: 2, (w: 3, z: 4)))
[r31892961_5].map { (x: Int, (y: Int, (w: Int, z: Int))) in x + y }
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-56=arg1}} {{61-61=let (y, (w, z)) = arg1; }}
let r31892961_6 = (x: 1, (y: 2, z: 4))
[r31892961_6].map { (x: Int, (y: Int, z: Int)) in x + y }
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-46=arg1}} {{51-51=let (y, z) = arg1; }}
// rdar://problem/32214649 -- these regressed in Swift 4 mode
// with SE-0110 because of a problem in associated type inference
func r32214649_1<X,Y>(_ a: [X], _ f: (X)->Y) -> [Y] {
return a.map(f)
}
func r32214649_2<X>(_ a: [X], _ f: (X) -> Bool) -> [X] {
return a.filter(f)
}
func r32214649_3<X>(_ a: [X]) -> [X] {
return a.filter { _ in return true }
}
// rdar://problem/32301091 - [SE-0110] causes errors when passing a closure with a single underscore to a block accepting multiple parameters
func rdar32301091_1(_ :((Int, Int) -> ())!) {}
rdar32301091_1 { _ in }
// expected-error@-1 {{cannot convert value of type '(_) -> ()' to expected argument type '((Int, Int) -> ())?'}}
func rdar32301091_2(_ :(Int, Int) -> ()) {}
rdar32301091_2 { _ in }
// expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,_ }}
rdar32301091_2 { x in }
// expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,<#arg#> }}
func rdar32875953() {
let myDictionary = ["hi":1]
myDictionary.forEach {
print("\($0) -> \($1)")
}
myDictionary.forEach { key, value in
print("\(key) -> \(value)")
}
myDictionary.forEach { (key, value) in
print("\(key) -> \(value)")
}
let array1 = [1]
let array2 = [2]
_ = zip(array1, array2).map(+)
}
struct SR_5199 {}
extension Sequence where Iterator.Element == (key: String, value: String?) {
func f() -> [SR_5199] {
return self.map { (key, value) in
SR_5199() // Ok
}
}
}
func rdar33043106(_ records: [(Int)], _ other: [((Int))]) -> [Int] {
let x: [Int] = records.map { _ in
let i = 1
return i
}
let y: [Int] = other.map { _ in
let i = 1
return i
}
return x + y
}
func itsFalse(_: Int) -> Bool? {
return false
}
func rdar33159366(s: AnySequence<Int>) {
_ = s.compactMap(itsFalse)
let a = Array(s)
_ = a.compactMap(itsFalse)
}
func sr5429<T>(t: T) {
_ = AnySequence([t]).first(where: { (t: T) in true })
}
extension Concrete {
typealias T = (Int, Int)
typealias F = (T) -> ()
func opt1(_ fn: (((Int, Int)) -> ())?) {}
func opt2(_ fn: (((Int, Int)) -> ())??) {}
func opt3(_ fn: (((Int, Int)) -> ())???) {}
func optAliasT(_ fn: ((T) -> ())?) {}
func optAliasF(_ fn: F?) {}
}
extension Generic {
typealias F = (T) -> ()
func opt1(_ fn: (((Int, Int)) -> ())?) {}
func opt2(_ fn: (((Int, Int)) -> ())??) {}
func opt3(_ fn: (((Int, Int)) -> ())???) {}
func optAliasT(_ fn: ((T) -> ())?) {}
func optAliasF(_ fn: F?) {}
}
func rdar33239714() {
Concrete().opt1 { x, y in }
Concrete().opt1 { (x, y) in }
Concrete().opt2 { x, y in }
Concrete().opt2 { (x, y) in }
Concrete().opt3 { x, y in }
Concrete().opt3 { (x, y) in }
Concrete().optAliasT { x, y in }
Concrete().optAliasT { (x, y) in }
Concrete().optAliasF { x, y in }
Concrete().optAliasF { (x, y) in }
Generic<(Int, Int)>().opt1 { x, y in }
Generic<(Int, Int)>().opt1 { (x, y) in }
Generic<(Int, Int)>().opt2 { x, y in }
Generic<(Int, Int)>().opt2 { (x, y) in }
Generic<(Int, Int)>().opt3 { x, y in }
Generic<(Int, Int)>().opt3 { (x, y) in }
Generic<(Int, Int)>().optAliasT { x, y in }
Generic<(Int, Int)>().optAliasT { (x, y) in }
Generic<(Int, Int)>().optAliasF { x, y in }
Generic<(Int, Int)>().optAliasF { (x, y) in }
}
// rdar://problem/35198459 - source-compat-suite failure: Moya (toType->hasUnresolvedType() && "Should have handled this above"
do {
func foo(_: (() -> Void)?) {}
func bar() -> ((()) -> Void)? { return nil }
foo(bar()) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}}
}
// https://bugs.swift.org/browse/SR-6509
public extension Optional {
public func apply<Result>(_ transform: ((Wrapped) -> Result)?) -> Result? {
return self.flatMap { value in
transform.map { $0(value) }
}
}
public func apply<Value, Result>(_ value: Value?) -> Result?
where Wrapped == (Value) -> Result {
return value.apply(self)
}
}
// https://bugs.swift.org/browse/SR-6837
do {
func takeFn(fn: (_ i: Int, _ j: Int?) -> ()) {}
func takePair(_ pair: (Int, Int?)) {}
takeFn(fn: takePair) // expected-error {{cannot convert value of type '((Int, Int?)) -> ()' to expected argument type '(Int, Int?) -> ()'}}
takeFn(fn: { (pair: (Int, Int?)) in } ) // Disallow for -swift-version 4 and later
// expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}}
takeFn { (pair: (Int, Int?)) in } // Disallow for -swift-version 4 and later
// expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
// https://bugs.swift.org/browse/SR-6796
do {
func f(a: (() -> Void)? = nil) {}
func log<T>() -> ((T) -> Void)? { return nil }
f(a: log() as ((()) -> Void)?) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}}
func logNoOptional<T>() -> (T) -> Void { }
f(a: logNoOptional() as ((()) -> Void)) // expected-error {{cannot convert value of type '(()) -> Void' to expected argument type '(() -> Void)?'}}
func g() {}
g(()) // expected-error {{argument passed to call that takes no arguments}}
func h(_: ()) {} // expected-note {{'h' declared here}}
h() // expected-error {{missing argument for parameter #1 in call}}
}
| apache-2.0 | 591e04a9a595051e451eaf424813da2b | 30.756724 | 187 | 0.618419 | 3.256451 | false | false | false | false |
BurntCaramel/Lantern | Lantern/AppDelegate.swift | 1 | 2715 | //
// AppDelegate.swift
// Hoverlytics for Mac
//
// Created by Patrick Smith on 28/03/2015.
// Copyright (c) 2015 Burnt Caramel. All rights reserved.
//
import Cocoa
import LanternModel
import Fabric
import Crashlytics
let NSApp = NSApplication.shared
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var browserMenuController: BrowserMenuController!
@IBOutlet var browserWidthPlaceholderMenuItem: NSMenuItem!
var crawlerMenuController: CrawlerMenuController!
@IBOutlet var crawlerImageDownloadPlaceholderMenuItem: NSMenuItem!
deinit {
let nc = NotificationCenter.default
for observer in windowWillCloseObservers {
nc.removeObserver(observer)
}
windowWillCloseObservers.removeAll()
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
Fabric.with([Crashlytics()])
// Create shared manager to ensure quickest start up time.
let modelManager = LanternModel.ModelManager.sharedManager
modelManager.errorReceiver.errorCallback = { error in
NSApp.presentError(error)
}
browserMenuController = BrowserMenuController(browserWidthPlaceholderMenuItem: browserWidthPlaceholderMenuItem)
crawlerMenuController = CrawlerMenuController(imageDownloadPlaceholderMenuItem: crawlerImageDownloadPlaceholderMenuItem)
#if DEBUG
// Update the bloody Dock icon
NSApp.applicationIconImage = nil
UserDefaults.standard.set(true, forKey: "NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints")
#endif
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
lazy var mainStoryboard: NSStoryboard = {
return NSStoryboard(name: "Main", bundle: nil)
}()
var mainWindowControllers = [MainWindowController]()
var windowWillCloseObservers = [AnyObject]()
func applicationOpenUntitledFile(_ sender: NSApplication) -> Bool {
let windowController = mainStoryboard.instantiateInitialController() as! MainWindowController
windowController.showWindow(nil)
mainWindowControllers.append(windowController)
let nc = NotificationCenter.default
windowWillCloseObservers.append(nc.addObserver(forName: NSWindow.willCloseNotification, object: windowController.window!, queue: nil, using: { [unowned self] note in
if let index = self.mainWindowControllers.index(of: windowController) {
self.mainWindowControllers.remove(at: index)
}
}))
return true
}
@IBAction func newDocument(_ sender: AnyObject?) {
_ = self.applicationOpenUntitledFile(NSApp)
}
@IBAction func forkOnGitHub(_ sender: AnyObject?) {
let URL = Foundation.URL(string: "https://github.com/BurntCaramel/Lantern")!
NSWorkspace.shared.open(URL)
}
}
| apache-2.0 | 730ce07dcf70ef017492cbb0a8036e21 | 28.51087 | 167 | 0.780847 | 4.421824 | false | false | false | false |
GYLibrary/GYHelpTools | GYHelpToolsSwift/GYHelpToolsSwift/GYTabbar/GYTabBarViewController.swift | 1 | 3057 | //
// GYTabBarViewController.swift
// GYHelpToolsSwift
//
// Created by ZGY on 2016/12/29.
// Copyright © 2016年 Giant. All rights reserved.
//
// Author: Airfight
// My GitHub: https://github.com/airfight
// My Blog: http://airfight.github.io/
// My Jane book: http://www.jianshu.com/users/17d6a01e3361
// Current Time: 2016/12/29 14:35
// GiantForJade: Efforts to do my best
// Real developers ship.
import UIKit
class GYTabBarViewController: UITabBarController {
//MARK: - Attributes
override func viewDidLoad() {
super.viewDidLoad()
let viewControlers = ["OneViewController",
"TwoViewController",
"ThreeViewController",
"FourViewController"]
for vcName in viewControlers {
//1.动态获取命名空间
let ns = Bundle.main.infoDictionary?["CFBundleExecutable"] as! String
let cls:AnyClass? = NSClassFromString(ns + "." + vcName)
//通过类创建对象
let vcCls = cls as! UIViewController.Type
let vc = vcCls.init()
vc.tabBarItem.image = UIImage(named: vcName)
//去掉系统渲染
//.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
vc.tabBarItem.selectedImage = UIImage(named: vcName + "_highlight")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
vc.title = vcName
vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: UIControlState.selected)
let nav = GYNavViewController()
nav.addChildViewController(vc)
addChildViewController(nav)
}
}
//MARK: - Override
//MARK: - Initial Methods
//MARK: - Delegate
//MARK: - Target Methods
//MARK: - Notification Methods
//MARK: - KVO Methods
//MARK: - UITableViewDelegate, UITableViewDataSource
//MARK: - Privater Methods
//MARK: - Setter Getter Methods
//MARK: - Life cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
deinit {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | d80dd05c3b1fdf9d7f218fd227dd1b11 | 25.654867 | 135 | 0.578021 | 5.229167 | false | false | false | false |
vmanot/swift-package-manager | Tests/BasicTests/PathShimTests.swift | 1 | 10568 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
import XCTest
import Basic
import POSIX
class PathShimTests : XCTestCase {
func testResolvingSymlinks() {
// Make sure the root path resolves to itself.
XCTAssertEqual(resolveSymlinks(AbsolutePath.root), AbsolutePath.root)
// For the rest of the tests we'll need a temporary directory.
let tmpDir = try! TemporaryDirectory(removeTreeOnDeinit: true)
// FIXME: it would be better to not need to resolve symbolic links, but we end up relying on /tmp -> /private/tmp.
let tmpDirPath = resolveSymlinks(tmpDir.path)
// Create a symbolic link and directory.
let slnkPath = tmpDirPath.appending(component: "slnk")
let fldrPath = tmpDirPath.appending(component: "fldr")
// Create a symbolic link pointing at the (so far non-existent) directory.
try! createSymlink(slnkPath, pointingAt: fldrPath, relative: true)
// Resolving the symlink should not yet change anything.
XCTAssertEqual(resolveSymlinks(slnkPath), slnkPath)
// Create a directory to be the referent of the symbolic link.
try! makeDirectories(fldrPath)
// Resolving the symlink should now point at the directory.
XCTAssertEqual(resolveSymlinks(slnkPath), fldrPath)
// Resolving the directory should still not change anything.
XCTAssertEqual(resolveSymlinks(fldrPath), fldrPath)
}
func testRescursiveDirectoryCreation() {
// For the tests we'll need a temporary directory.
let tmpDir = try! TemporaryDirectory(removeTreeOnDeinit: true)
// Create a directory under several ancestor directories.
let dirPath = tmpDir.path.appending(components: "abc", "def", "ghi", "mno", "pqr")
try! makeDirectories(dirPath)
// Check that we were able to actually create the directory.
XCTAssertTrue(isDirectory(dirPath))
// Check that there's no error if we try to create the directory again.
try! makeDirectories(dirPath)
}
func testRecursiveDirectoryRemoval() {
// For the tests we'll need a temporary directory.
let tmpDir = try! TemporaryDirectory(removeTreeOnDeinit: true)
// FIXME: it would be better to not need to resolve symbolic links, but we end up relying on /tmp -> /private/tmp.
let tmpDirPath = resolveSymlinks(tmpDir.path)
// Create a couple of directories. The first one shouldn't end up getting removed, the second one will.
let keepDirPath = tmpDirPath.appending(components: "abc1")
try! makeDirectories(keepDirPath)
let tossDirPath = tmpDirPath.appending(components: "abc2", "def", "ghi", "mno", "pqr")
try! makeDirectories(tossDirPath)
// Create a symbolic link in a directory to be removed; it points to a directory to not remove.
let slnkPath = tossDirPath.appending(components: "slnk")
try! createSymlink(slnkPath, pointingAt: keepDirPath, relative: true)
// Make sure the symbolic link got set up correctly.
XCTAssertTrue(isSymlink(slnkPath))
XCTAssertEqual(resolveSymlinks(slnkPath), keepDirPath)
XCTAssertTrue(isDirectory(resolveSymlinks(slnkPath)))
// Now remove the directory hierarchy that contains the symlink.
try! removeFileTree(tossDirPath)
// Make sure it got removed, along with the symlink, but that the target of the symlink remains.
XCTAssertFalse(exists(tossDirPath))
XCTAssertFalse(isDirectory(tossDirPath))
XCTAssertTrue(exists(keepDirPath))
XCTAssertTrue(isDirectory(keepDirPath))
}
func testCurrentWorkingDirectory() {
// Test against what POSIX returns, at least for now.
let cwd = currentWorkingDirectory;
XCTAssertEqual(cwd, AbsolutePath(getcwd()))
}
static var allTests = [
("testResolvingSymlinks", testResolvingSymlinks),
("testRescursiveDirectoryCreation", testRescursiveDirectoryCreation),
("testRecursiveDirectoryRemoval", testRecursiveDirectoryRemoval),
("testCurrentWorkingDirectory", testCurrentWorkingDirectory)
]
}
class WalkTests : XCTestCase {
func testNonRecursive() {
var expected = [
AbsolutePath("/usr"),
AbsolutePath("/bin"),
AbsolutePath("/sbin")
]
for x in try! walk(AbsolutePath("/"), recursively: false) {
if let i = expected.index(of: x) {
expected.remove(at: i)
}
XCTAssertEqual(2, x.components.count)
}
XCTAssertEqual(expected.count, 0)
}
func testRecursive() {
let root = AbsolutePath(#file).parentDirectory.parentDirectory.parentDirectory.appending(component: "Sources")
var expected = [
root.appending(component: "Build"),
root.appending(component: "Utility")
]
for x in try! walk(root) {
if let i = expected.index(of: x) {
expected.remove(at: i)
}
}
XCTAssertEqual(expected.count, 0)
}
func testSymlinksNotWalked() {
let tmpDir = try! TemporaryDirectory(removeTreeOnDeinit: true)
// FIXME: it would be better to not need to resolve symbolic links, but we end up relying on /tmp -> /private/tmp.
let tmpDirPath = resolveSymlinks(tmpDir.path)
try! makeDirectories(tmpDirPath.appending(component: "foo"))
try! makeDirectories(tmpDirPath.appending(components: "bar", "baz", "goo"))
try! createSymlink(tmpDirPath.appending(components: "foo", "symlink"), pointingAt: tmpDirPath.appending(component: "bar"), relative: true)
XCTAssertTrue(isSymlink(tmpDirPath.appending(components: "foo", "symlink")))
XCTAssertEqual(resolveSymlinks(tmpDirPath.appending(components: "foo", "symlink")), tmpDirPath.appending(component: "bar"))
XCTAssertTrue(isDirectory(resolveSymlinks(tmpDirPath.appending(components: "foo", "symlink", "baz"))))
let results = try! walk(tmpDirPath.appending(component: "foo")).map{ $0 }
XCTAssertEqual(results, [tmpDirPath.appending(components: "foo", "symlink")])
}
func testWalkingADirectorySymlinkResolvesOnce() {
let tmpDir = try! TemporaryDirectory(removeTreeOnDeinit: true)
let tmpDirPath = tmpDir.path
try! makeDirectories(tmpDirPath.appending(components: "foo", "bar"))
try! makeDirectories(tmpDirPath.appending(components: "abc", "bar"))
try! createSymlink(tmpDirPath.appending(component: "symlink"), pointingAt: tmpDirPath.appending(component: "foo"), relative: true)
try! createSymlink(tmpDirPath.appending(components: "foo", "baz"), pointingAt: tmpDirPath.appending(component: "abc"), relative: true)
XCTAssertTrue(isSymlink(tmpDirPath.appending(component: "symlink")))
let results = try! walk(tmpDirPath.appending(component: "symlink")).map{ $0 }.sorted()
// we recurse a symlink to a directory, so this should work,
// but `abc` should not show because `baz` is a symlink too
// and that should *not* be followed
XCTAssertEqual(results, [tmpDirPath.appending(components: "symlink", "bar"), tmpDirPath.appending(components: "symlink", "baz")])
}
static var allTests = [
("testNonRecursive", testNonRecursive),
("testRecursive", testRecursive),
("testSymlinksNotWalked", testSymlinksNotWalked),
("testWalkingADirectorySymlinkResolvesOnce", testWalkingADirectorySymlinkResolvesOnce),
]
}
class FileAccessTests : XCTestCase {
private func loadInputFile(_ name: String) throws -> FileHandle {
let input = AbsolutePath(#file).parentDirectory.appending(components: "Inputs", name)
return try fopen(input, mode: .read)
}
func testOpenFile() {
do {
let file = try loadInputFile("empty_file")
XCTAssertEqual(try file.readFileContents(), "")
} catch {
XCTFail("The file should be opened without problem")
}
}
func testOpenFileFail() {
do {
let file = try loadInputFile("file_not_existing")
let _ = try file.readFileContents()
XCTFail("The file should not be opened since it is not existing")
} catch {
}
}
func testReadRegularTextFile() {
do {
let file = try loadInputFile("regular_text_file")
var generator = try file.readFileContents().components(separatedBy: "\n").makeIterator()
XCTAssertEqual(generator.next(), "Hello world")
XCTAssertEqual(generator.next(), "It is a regular text file.")
XCTAssertEqual(generator.next(), "")
XCTAssertNil(generator.next())
} catch {
XCTFail("The file should be opened without problem")
}
}
func testReadRegularTextFileWithSeparator() {
do {
let file = try loadInputFile("regular_text_file")
var generator = try file.readFileContents().components(separatedBy: " ").makeIterator()
XCTAssertEqual(generator.next(), "Hello")
XCTAssertEqual(generator.next(), "world\nIt")
XCTAssertEqual(generator.next(), "is")
XCTAssertEqual(generator.next(), "a")
XCTAssertEqual(generator.next(), "regular")
XCTAssertEqual(generator.next(), "text")
XCTAssertEqual(generator.next(), "file.\n")
XCTAssertNil(generator.next())
} catch {
XCTFail("The file should be opened without problem")
}
}
static var allTests = [
("testOpenFile", testOpenFile),
("testOpenFileFail", testOpenFileFail),
("testReadRegularTextFile", testReadRegularTextFile),
("testReadRegularTextFileWithSeparator", testReadRegularTextFileWithSeparator),
]
}
| apache-2.0 | 9d8f7e911046356169f478a040e9e3d1 | 41.612903 | 146 | 0.640613 | 4.83219 | false | true | false | false |
jingweiwoo/FlyStream | FlyStreamPlayer/ViewController/BaseViewController/BaseViewController.swift | 1 | 1411 | //
// BaseViewController.swift
// FlyStream
//
// Created by Jingwei Wu on 05/03/2017.
// Copyright © 2017 jingweiwu. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
var animatedOnNavigationBar = true
var viewTitle: String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Do any additional setup after loading the view.
self.navigationItem.title = viewTitle
let tempNavigationBackButton = UIBarButtonItem()
tempNavigationBackButton.title = self.viewTitle
self.navigationItem.backBarButtonItem = tempNavigationBackButton
guard let navigationController = navigationController else {
return
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 81647b66710ebde517ae9e3b645383d2 | 26.647059 | 106 | 0.656738 | 5.402299 | false | false | false | false |
illescasDaniel/Questions | Questions/config/AppDelegate.swift | 1 | 5382 | import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var wasPlaying = Bool()
private let blurView = UIVisualEffectView(frame: UIScreen.main.bounds)
// Home Screen Quick Actions [3D Touch]
enum ShortcutItemType: String {
case QRCode
}
// if you can use AppDelegate.Windows in other way, delete this
static var windowReference: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
if #available(iOS 13, *) {}
else {
let sideVolumeTheme: SideVolumeHUD.Option.Theme = UserDefaultsManager.darkThemeSwitchIsOn ? .dark : .light
SideVolumeHUD.shared.setup(withOptions: [.animationStyle(.slideLeftRight), .theme(sideVolumeTheme)])
}
self.setupURLCache()
self.loadConfigFiles()
self.preferLargeTitles()
self.setupAppShorcuts(for: application)
self.setupPrivacyFeatures()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
guard QuestionsAppOptions.privacyFeaturesEnabled else { return }
self.blurView.isHidden = false
self.window?.bringSubviewToFront(blurView)
}
func applicationDidBecomeActive(_ application: UIApplication) {
if self.wasPlaying {
AudioSounds.bgMusic?.play()
}
self.window?.dontInvertIfDarkModeIsEnabled()
if QuestionsAppOptions.privacyFeaturesEnabled {
self.blurView.isHidden = true
}
}
@available(iOS 9.0, *)
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
if let itemType = ShortcutItemType(rawValue: shortcutItem.type) {
switch itemType {
case .QRCode:
if let questionsVC = window?.rootViewController?.presentedViewController as? QuestionsViewController {
questionsVC.performSegue(withIdentifier: "unwindToMainMenu", sender: self)
}
if let presentedViewController = window?.rootViewController as? UINavigationController {
if presentedViewController.topViewController is QRScannerViewController {
return
} else if !(presentedViewController.topViewController is MainViewController) {
presentedViewController.popToRootViewController(animated: false)
}
presentedViewController.topViewController?.performSegue(withIdentifier: "QRScannerVC", sender: self)
}
else if (window?.rootViewController == nil) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let viewController = storyboard.instantiateViewController(withIdentifier: "mainViewController") as? MainViewController {
let navController = UINavigationController(rootViewController: viewController)
if #available(iOS 11.0, *) {
navController.navigationBar.prefersLargeTitles = true
}
window?.rootViewController?.present(navController, animated: false)
viewController.performSegue(withIdentifier: "QRScannerVC", sender: self)
}
}
}
}
}
func applicationDidEnterBackground(_ application: UIApplication) {
if AudioSounds.bgMusic?.isPlaying ?? false {
AudioSounds.bgMusic?.pause()
wasPlaying = true
}
else {
wasPlaying = false
}
guard DataStoreArchiver.shared.save() else { print("Error saving settings"); return }
self.window?.dontInvertIfDarkModeIsEnabled()
}
// - MARK: Convenience
private func setupURLCache() {
URLCache.shared.diskCapacity = 150 * 1024 * 1024
URLSession.shared.configuration.requestCachePolicy = .returnCacheDataElseLoad
}
// Load configuration file (if it doesn't exist it creates a new one when the app goes to background)
private func loadConfigFiles() {
if #available(iOS 11, *) {
if let settingsData = try? Data(contentsOf: URL(fileURLWithPath: DataStoreArchiver.path)),
let mySettings = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(settingsData) as? DataStoreArchiver{
DataStoreArchiver.shared = mySettings
}
} else {
if let mySettings = NSKeyedUnarchiver.unarchiveObject(withFile: DataStoreArchiver.path) as? DataStoreArchiver {
DataStoreArchiver.shared = mySettings
}
}
}
private func preferLargeTitles() {
let navController = window?.rootViewController as? UINavigationController
if #available(iOS 11.0, *) {
navController?.navigationBar.prefersLargeTitles = true
}
}
private func setupAppShorcuts(for application: UIApplication) {
let readQRCode = UIMutableApplicationShortcutItem(type: ShortcutItemType.QRCode.rawValue,
localizedTitle: L10n.HomeQuickActions_ScanQR,
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: "QRCodeIcon"))
application.shortcutItems = [readQRCode]
}
private func setupWindow() {
AppDelegate.windowReference = self.window
self.window?.dontInvertIfDarkModeIsEnabled()
}
private func setupPrivacyFeatures() {
if QuestionsAppOptions.privacyFeaturesEnabled {
self.setupBlurView()
}
}
private func setupBlurView() {
self.blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.blurView.effect = UserDefaultsManager.darkThemeSwitchIsOn ? UIBlurEffect(style: .dark) : UIBlurEffect(style: .light)
self.blurView.isHidden = true
self.window?.addSubview(blurView)
}
}
| mit | 0e63952414adc7ab05cb73829e0875bb | 31.618182 | 152 | 0.742103 | 4.4701 | false | false | false | false |
MukeshKumarS/Swift | test/ClangModules/objc_parse.swift | 1 | 21570 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -enable-swift-name-lookup-tables -I %S/Inputs/custom-modules %s -verify
// REQUIRES: objc_interop
import AppKit
import AVFoundation
import objc_ext
import TestProtocols
import ObjCParseExtras
import ObjCParseExtrasToo
import ObjCParseExtrasSystem
func markUsed<T>(t: T) {}
func testAnyObject(obj: AnyObject) {
_ = obj.nsstringProperty
}
// Construction
func construction() {
_ = B()
}
// Subtyping
func treatBAsA(b: B) -> A {
return b
}
// Instance method invocation
func instanceMethods(b: B) {
var i = b.method(1, withFloat:2.5)
i = i + b.method(1, withDouble:2.5)
// BOOL
b.setEnabled(true)
// SEL
b.performSelector("isEqual:", withObject:b)
if let result = b.performSelector("getAsProto", withObject:nil) {
_ = result.takeUnretainedValue()
}
// Renaming of redundant parameters.
b.performAdd(1, withValue:2, withValue2:3, withValue:4) // expected-error{{argument 'withValue' must precede argument 'withValue2'}}
b.performAdd(1, withValue:2, withValue:4, withValue2: 3)
b.performAdd(1, 2, 3, 4) // expected-error{{missing argument labels 'withValue:withValue:withValue2:' in call}} {{19-19=withValue: }} {{22-22=withValue: }} {{25-25=withValue2: }}
// Both class and instance methods exist.
b.description
b.instanceTakesObjectClassTakesFloat(b)
b.instanceTakesObjectClassTakesFloat(2.0) // expected-error{{cannot convert value of type 'Double' to expected argument type 'AnyObject!'}}
// Instance methods with keyword components
var obj = NSObject()
var prot = NSObjectProtocol.self
b.`protocol`(prot, hasThing:obj)
b.doThing(obj, `protocol`: prot)
}
// Class method invocation
func classMethods(b: B, other: NSObject) {
var i = B.classMethod()
i += B.classMethod(1)
i += B.classMethod(1, withInt:2)
i += b.classMethod() // expected-error{{static member 'classMethod' cannot be used on instance of type 'B'}}
// Both class and instance methods exist.
B.description()
B.instanceTakesObjectClassTakesFloat(2.0)
B.instanceTakesObjectClassTakesFloat(other) // expected-error{{cannot convert value of type 'NSObject' to expected argument type 'Float'}}
// Call an instance method of NSObject.
var c: AnyClass = B.myClass() // no-warning
c = b.myClass() // no-warning
}
// Instance method invocation on extensions
func instanceMethodsInExtensions(b: B) {
b.method(1, onCat1:2.5)
b.method(1, onExtA:2.5)
b.method(1, onExtB:2.5)
b.method(1, separateExtMethod:3.5)
let m1 = b.method:onCat1:
m1(1, onCat1: 2.5)
let m2 = b.method:onExtA:
m2(1, onExtA: 2.5)
let m3 = b.method:onExtB:
m3(1, onExtB: 2.5)
let m4 = b.method:separateExtMethod:
m4(1, separateExtMethod: 2.5)
}
func dynamicLookupMethod(b: AnyObject) {
// FIXME: Syntax will be replaced.
if let m5 = b.method:separateExtMethod: {
m5(1, separateExtMethod: 2.5)
}
}
// Properties
func properties(b: B) {
var i = b.counter
b.counter = i + 1
i = i + b.readCounter
b.readCounter = i + 1 // expected-error{{cannot assign to property: 'readCounter' is a get-only property}}
b.setCounter(5) // expected-error{{value of type 'B' has no member 'setCounter'}}
// Informal properties in Objective-C map to methods, not variables.
b.informalProp()
// An informal property cannot be made formal in a subclass. The
// formal property is simply ignored.
b.informalMadeFormal()
b.informalMadeFormal = i // expected-error{{cannot assign to property: 'b' is a 'let' constant}}
b.setInformalMadeFormal(5)
b.overriddenProp = 17
// Dynamic properties.
var obj : AnyObject = b
var optStr = obj.nsstringProperty
if optStr != nil {
var s : String = optStr!
}
// Properties that are Swift keywords
var prot = b.`protocol`
}
// Construction.
func newConstruction(a: A, aproxy: AProxy) {
var b : B = B()
b = B(int: 17)
b = B(int:17)
b = B(double:17.5, 3.14159)
b = B(BBB:b)
b = B(forWorldDomination:())
b = B(int: 17, andDouble : 3.14159)
b = B.newWithA(a)
B.alloc()._initFoo()
b.notAnInit()
// init methods are not imported by themselves.
b.initWithInt(17) // expected-error{{value of type 'B' has no member 'initWithInt'}}
// init methods on non-NSObject-rooted classes
AProxy(int: 5) // expected-warning{{unused}}
}
// Indexed subscripting
func indexedSubscripting(b: B, idx: Int, a: A) {
b[idx] = a
_ = b[idx] as! A
}
// Keyed subscripting
func keyedSubscripting(b: B, idx: A, a: A) {
b[a] = a
var a2 = b[a] as! A
let dict = NSMutableDictionary()
dict[NSString()] = a
let value = dict[NSString()]
dict[nil] = a // expected-error {{nil is not compatible with expected argument type 'NSCopying'}}
let q = dict[nil] // expected-error {{nil is not compatible with expected argument type 'NSCopying'}}
_ = q
}
// Typed indexed subscripting
func checkHive(hive: Hive, b: Bee) {
let b2 = hive.bees[5] as Bee
b2.buzz()
}
// Protocols
func testProtocols(b: B, bp: BProto) {
var bp2 : BProto = b
var b2 : B = bp // expected-error{{cannot convert value of type 'BProto' to specified type 'B'}}
bp.method(1, withFloat:2.5)
bp.method(1, withDouble:2.5) // expected-error{{incorrect argument label in call (have '_:withDouble:', expected '_:withFloat:')}} {{16-26=withFloat}}
bp2 = b.getAsProto()
var c1 : Cat1Proto = b
var bcat1 = b.getAsProtoWithCat()
c1 = bcat1
bcat1 = c1 // expected-error{{cannot assign value of type 'Cat1Proto' to type 'protocol<BProto, Cat1Proto>!'}}
}
// Methods only defined in a protocol
func testProtocolMethods(b: B, p2m: P2.Type) {
b.otherMethod(1, withFloat:3.14159)
b.p2Method()
b.initViaP2(3.14159, second:3.14159) // expected-error{{value of type 'B' has no member 'initViaP2'}}
// Imported constructor.
var b2 = B(viaP2: 3.14159, second:3.14159)
p2m.init(viaP2:3.14159, second: 3.14159)
}
func testId(x: AnyObject) {
x.performSelector!("foo:", withObject: x)
x.performAdd(1, withValue: 2, withValue: 3, withValue2: 4)
x.performAdd!(1, withValue: 2, withValue: 3, withValue2: 4)
x.performAdd?(1, withValue: 2, withValue: 3, withValue2: 4)
}
class MySubclass : B {
// Override a regular method.
override func anotherMethodOnB() {}
// Override a category method
override func anotherCategoryMethod() {}
}
func getDescription(array: NSArray) {
array.description
}
// Method overriding with unfortunate ordering.
func overridingTest(srs: SuperRefsSub) {
let rs : RefedSub
rs.overridden()
}
func almostSubscriptableValueMismatch(as1: AlmostSubscriptable, a: A) {
as1[a] // expected-error{{type 'AlmostSubscriptable' has no subscript members}}
}
func almostSubscriptableKeyMismatch(bc: BadCollection, key: NSString) {
// FIXME: We end up importing this as read-only due to the mismatch between
// getter/setter element types.
var _ : AnyObject = bc[key]
}
func almostSubscriptableKeyMismatchInherited(bc: BadCollectionChild,
key: String) {
var value : AnyObject = bc[key] // no-warning, inherited from parent
bc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}}
}
func almostSubscriptableKeyMismatchInherited(roc: ReadOnlyCollectionChild,
key: String) {
var value : AnyObject = roc[key] // no-warning, inherited from parent
roc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}}
}
// Use of 'Class' via dynamic lookup.
func classAnyObject(obj: NSObject) {
obj.myClass().description!()
}
// Protocol conformances
class Wobbler : NSWobbling { // expected-note{{candidate is not '@objc', but protocol requires it}} {{7-7=@objc }}
// expected-error@-1{{type 'Wobbler' does not conform to protocol 'NSWobbling'}}
@objc func wobble() { }
func returnMyself() -> Self { return self } // expected-note{{candidate is not '@objc', but protocol requires it}} {{3-3=@objc }}
}
extension Wobbler : NSMaybeInitWobble { // expected-error{{type 'Wobbler' does not conform to protocol 'NSMaybeInitWobble'}}
}
@objc class Wobbler2 : NSObject, NSWobbling { // expected-note{{Objective-C method 'init' provided by implicit initializer 'init()' does not match the requirement's selector ('initWithWobble:')}}
func wobble() { }
func returnMyself() -> Self { return self }
}
extension Wobbler2 : NSMaybeInitWobble { // expected-error{{type 'Wobbler2' does not conform to protocol 'NSMaybeInitWobble'}}
}
func optionalMemberAccess(w: NSWobbling) {
w.wobble()
w.wibble() // expected-error{{value of optional type '(() -> Void)?' not unwrapped; did you mean to use '!' or '?'?}} {{11-11=!}}
var x: AnyObject = w[5] // expected-error{{value of optional type 'AnyObject!?' not unwrapped; did you mean to use '!' or '?'?}} {{26-26=!}}
}
func protocolInheritance(s: NSString) {
var _: NSCoding = s
}
func ivars(hive: Hive) {
var d = hive.bees.description
hive.queen.description() // expected-error{{value of type 'Hive' has no member 'queen'}}
}
class NSObjectable : NSObjectProtocol {
@objc var description : String { return "" }
@objc func conformsToProtocol(_: Protocol) -> Bool { return false }
@objc func isKindOfClass(aClass: AnyClass) -> Bool { return false }
}
// Properties with custom accessors
func customAccessors(hive: Hive, bee: Bee) {
markUsed(hive.makingHoney)
markUsed(hive.isMakingHoney()) // expected-error{{value of type 'Hive' has no member 'isMakingHoney'}}
hive.setMakingHoney(true) // expected-error{{value of type 'Hive' has no member 'setMakingHoney'}}
hive.`guard`.description // okay
hive.`guard`.description! // no-warning
hive.`guard` = bee // no-warning
}
// instancetype/Dynamic Self invocation.
func testDynamicSelf(queen: Bee, wobbler: NSWobbling) {
var hive = Hive()
// Factory method with instancetype result.
var hive1 = Hive(queen: queen)
hive1 = hive
hive = hive1
// Instance method with instancetype result.
var hive2 = hive.visit()
hive2 = hive
hive = hive2
// Instance method on a protocol with instancetype result.
var wobbler2 = wobbler.returnMyself()
var wobbler: NSWobbling = wobbler2
wobbler2 = wobbler
// Instance method on a base class with instancetype result, called on the
// class itself.
// FIXME: This should be accepted.
// FIXME: The error is lousy, too.
let baseClass: ObjCParseExtras.Base.Type = ObjCParseExtras.Base.returnMyself() // expected-error{{missing argument for parameter #1 in call}}
}
func testRepeatedProtocolAdoption(w: NSWindow) {
w.description
}
class ProtocolAdopter1 : FooProto {
@objc var bar: CInt // no-warning
init() { bar = 5 }
}
class ProtocolAdopter2 : FooProto {
@objc var bar: CInt {
get { return 42 }
set { /* do nothing! */ }
}
}
class ProtocolAdopterBad1 : FooProto { // expected-error{{type 'ProtocolAdopterBad1' does not conform to protocol 'FooProto'}}
@objc var bar: Int = 0 // expected-note{{candidate has non-matching type 'Int'}}
}
class ProtocolAdopterBad2 : FooProto { // expected-error{{type 'ProtocolAdopterBad2' does not conform to protocol 'FooProto'}}
let bar: CInt = 0 // expected-note{{candidate is not settable, but protocol requires it}}
}
class ProtocolAdopterBad3 : FooProto { // expected-error{{type 'ProtocolAdopterBad3' does not conform to protocol 'FooProto'}}
var bar: CInt { // expected-note{{candidate is not settable, but protocol requires it}}
return 42
}
}
@objc protocol RefinedFooProtocol : FooProto {}
func testPreferClassMethodToCurriedInstanceMethod(obj: NSObject) {
// FIXME: We shouldn't need the ": Bool" type annotation here.
// <rdar://problem/18006008>
let _: Bool = NSObject.isEqual(obj)
_ = NSObject.isEqual(obj) as (NSObject!) -> Bool // no-warning
}
func testPropertyAndMethodCollision(obj: PropertyAndMethodCollision,
rev: PropertyAndMethodReverseCollision) {
obj.object = nil
obj.object(obj, doSomething:"action")
rev.object = nil
rev.object(rev, doSomething:"action")
var value: AnyObject = obj.protoProp()
value = obj.protoPropRO()
_ = value
}
func testSubscriptAndPropertyRedeclaration(obj: SubscriptAndProperty) {
_ = obj.x
obj.x = 5
obj.objectAtIndexedSubscript(5) // expected-error{{'objectAtIndexedSubscript' is unavailable: use subscripting}}
obj.setX(5) // expected-error{{value of type 'SubscriptAndProperty' has no member 'setX'}}
_ = obj[0]
obj[1] = obj
obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}}
}
func testSubscriptAndPropertyWithProtocols(obj: SubscriptAndPropertyWithProto) {
_ = obj.x
obj.x = 5
obj.setX(5) // expected-error{{value of type 'SubscriptAndPropertyWithProto' has no member 'setX'}}
_ = obj[0]
obj[1] = obj
obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}}
}
func testProtocolMappingSameModule(obj: AVVideoCompositionInstruction, p: AVVideoCompositionInstructionProtocol) {
markUsed(p.enablePostProcessing)
markUsed(obj.enablePostProcessing)
_ = obj.backgroundColor
}
func testProtocolMappingDifferentModules(obj: ObjCParseExtrasToo.ProtoOrClass, p: ObjCParseExtras.ProtoOrClass) {
markUsed(p.thisIsTheProto)
markUsed(obj.thisClassHasAnAwfulName)
let _: ProtoOrClass? // expected-error{{'ProtoOrClass' is ambiguous for type lookup in this context}}
_ = ObjCParseExtrasToo.ClassInHelper() // expected-error{{'ClassInHelper' cannot be constructed because it has no accessible initializers}}
_ = ObjCParseExtrasToo.ProtoInHelper()
_ = ObjCParseExtrasTooHelper.ClassInHelper()
_ = ObjCParseExtrasTooHelper.ProtoInHelper() // expected-error{{'ProtoInHelper' cannot be constructed because it has no accessible initializers}}
}
func testProtocolClassShadowing(obj: ClassInHelper, p: ProtoInHelper) {
let _: ObjCParseExtrasToo.ClassInHelper = obj
let _: ObjCParseExtrasToo.ProtoInHelper = p
}
func testDealloc(obj: NSObject) {
// dealloc is subsumed by deinit.
// FIXME: Special-case diagnostic in the type checker?
obj.dealloc() // expected-error{{value of type 'NSObject' has no member 'dealloc'}}
}
func testConstantGlobals() {
markUsed(MAX)
markUsed(SomeImageName)
markUsed(SomeNumber.description)
MAX = 5 // expected-error{{cannot assign to value: 'MAX' is a 'let' constant}}
SomeImageName = "abc" // expected-error{{cannot assign to value: 'SomeImageName' is a 'let' constant}}
SomeNumber = nil // expected-error{{cannot assign to value: 'SomeNumber' is a 'let' constant}}
}
func testWeakVariable() {
let _: AnyObject = globalWeakVar
}
class IncompleteProtocolAdopter : Incomplete, IncompleteOptional { // expected-error {{type 'IncompleteProtocolAdopter' cannot conform to protocol 'Incomplete' because it has requirements that cannot be satisfied}}
@objc func getObject() -> AnyObject { return self }
}
func testNullarySelectorPieces(obj: AnyObject) {
obj.foo(1, bar: 2, 3) // no-warning
obj.foo(1, 2, bar: 3) // expected-error{{cannot call value of non-function type 'AnyObject?!'}}
}
func testFactoryMethodAvailability() {
_ = DeprecatedFactoryMethod() // expected-warning{{'init()' is deprecated: use something newer}}
}
func testRepeatedMembers(obj: RepeatedMembers) {
obj.repeatedMethod()
}
// rdar://problem/19726164
class FooDelegateImpl : NSObject, FooDelegate {
var _started = false
var started: Bool {
@objc(isStarted) get { return _started }
set { _started = newValue }
}
}
class ProtoAdopter : NSObject, ExplicitSetterProto, OptionalSetterProto {
var foo: AnyObject? // no errors about conformance
var bar: AnyObject? // no errors about conformance
}
func testUnusedResults(ur: UnusedResults) {
_ = ur.producesResult()
ur.producesResult() // expected-warning{{result of call to 'producesResult()' is unused}}
}
func testCStyle() {
ExtraSelectors.cStyle(0, 1, 2) // expected-error{{type 'ExtraSelectors' has no member 'cStyle'}}
}
func testProtocolQualified(obj: CopyableNSObject, cell: CopyableSomeCell,
plainObj: NSObject, plainCell: SomeCell) {
_ = obj as NSObject // expected-error {{'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>') is not convertible to 'NSObject'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}}
_ = obj as NSObjectProtocol
_ = obj as NSCopying
_ = obj as SomeCell // expected-error {{'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>') is not convertible to 'SomeCell'; did you mean to use 'as!' to force downcast?}} {{11-13=as!}}
_ = cell as NSObject
_ = cell as NSObjectProtocol
_ = cell as NSCopying // expected-error {{'CopyableSomeCell' (aka 'SomeCell') is not convertible to 'NSCopying'; did you mean to use 'as!' to force downcast?}} {{12-14=as!}}
_ = cell as SomeCell
_ = plainObj as CopyableNSObject // expected-error {{'NSObject' is not convertible to 'CopyableNSObject' (aka 'protocol<NSCopying, NSObjectProtocol>'); did you mean to use 'as!' to force downcast?}} {{16-18=as!}}
_ = plainCell as CopyableSomeCell // FIXME: This is not really typesafe.
}
extension Printing {
func testImplicitWarnUnqualifiedAccess() {
print() // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self) // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self, options: self) // no-warning
}
static func testImplicitWarnUnqualifiedAccess() {
print() // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self) // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}}
// expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}}
// expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}}
print(self, options: self) // no-warning
}
}
// <rdar://problem/21979968> The "with array" initializers for NSCountedSet and NSMutable set should be properly disambiguated.
func testSetInitializers() {
let a: [AnyObject] = [NSObject()]
let _ = NSCountedSet(array: a)
let _ = NSMutableSet(array: a)
}
func testNSUInteger(obj: NSUIntegerTests, uint: UInt, int: Int) {
obj.consumeUnsigned(uint) // okay
obj.consumeUnsigned(int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
obj.consumeUnsigned(0, withTheNSUIntegerHere: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.consumeUnsigned(0, withTheNSUIntegerHere: int) // okay
obj.consumeUnsigned(uint, andAnother: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.consumeUnsigned(uint, andAnother: int) // okay
do {
let x = obj.unsignedProducer()
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
do {
obj.unsignedProducer(uint, fromCount: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.unsignedProducer(int, fromCount: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = obj.unsignedProducer(uint, fromCount: int) // okay
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
do {
obj.normalProducer(uint, fromUnsigned: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
obj.normalProducer(int, fromUnsigned: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = obj.normalProducer(int, fromUnsigned: uint)
let _: String = x // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
}
let _: String = obj.normalProp // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let _: String = obj.unsignedProp // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
do {
testUnsigned(int, uint) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
testUnsigned(uint, int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let x = testUnsigned(uint, uint) // okay
let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
// NSNumber
NSNumber(unsignedInteger: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
let num = NSNumber(unsignedInteger: uint)
let _: String = num.unsignedIntegerValue // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}}
}
| apache-2.0 | b04d48b21a2d465941c2cb6d830471e4 | 35.497462 | 214 | 0.702689 | 3.901954 | false | true | false | false |
sublimter/Meijiabang | KickYourAss/KickYourAss/ICYProfileViewController.swift | 3 | 5422 | //
// ICYProfileViewController.swift
// KickYourAss
//
// Created by eagle on 15/2/9.
// Copyright (c) 2015年 多思科技. All rights reserved.
//
import UIKit
class ICYProfileViewController: UITableViewController {
var userInfo: CYMJUserInfoData!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell!
// Configure the cell...
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
cell = tableView.dequeueReusableCellWithIdentifier(ICYProfileAvatarCell.identifier) as UITableViewCell
let cell = cell as ICYProfileAvatarCell
cell.icyMainLabel.text = "头像"
cell.imagePath = userInfo.headImage.toAbsoluteImagePath()
case 1:
cell = tableView.dequeueReusableCellWithIdentifier(ICYProfileCell.identifier) as UITableViewCell
let cell = cell as ICYProfileCell
cell.icyMainLabel.text = "昵称"
cell.icyDetailLabel?.text = userInfo.nickName
case 2:
cell = tableView.dequeueReusableCellWithIdentifier(ICYProfileCell.identifier) as UITableViewCell
let cell = cell as ICYProfileCell
cell.icyMainLabel.text = "性别"
var sex: String = userInfo.sex ?? "3"
cell.icyDetailLabel.text = userInfo.sex == "1" ? "男" : userInfo.sex == "2" ? "女" : "未知"
default:
break
}
case 1:
cell = tableView.dequeueReusableCellWithIdentifier(ICYProfileCell.identifier) as UITableViewCell
let cell = cell as ICYProfileCell
switch indexPath.row {
case 0:
cell.icyMainLabel.text = "注册电话"
cell.icyDetailLabel.text = userInfo.tel.checkNull()
case 1:
cell.icyMainLabel.text = "真实姓名"
cell.icyDetailLabel.text = userInfo.realName.checkNull()
case 2:
cell.icyMainLabel.text = "常用地址"
cell.icyDetailLabel.text = userInfo.address.checkNull()
default:
break
}
default:
break
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 0 {
return 60.0
} else {
return 44.0
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0a92645f6d47f3c5648060c37b1355ef | 35.767123 | 157 | 0.632638 | 5.341294 | false | false | false | false |
1170197998/SinaWeibo | SFWeiBo/SFWeiBo/Classes/Profile/SetupViewController.swift | 1 | 3104 | //
// SetupViewController.swift
// SFWeiBo
//
// Created by ShaoFeng on 16/6/13.
// Copyright © 2016年 ShaoFeng. All rights reserved.
//
import UIKit
let cellIdentifier = "cellIdentifier"
class SetupViewController: UITableViewController {
let arrayTitle1 = ["账号管理","账号安全"]
let arrayTitle2 = ["通知","隐私","通用设置"]
let arrayTitle3 = ["清除缓存","意见反馈","关于微博"]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "设置"
tableView.tableFooterView = UIView()
tableView.backgroundColor = UIColor(red: 229 / 255, green: 228/255, blue: 229/255, alpha: 1)
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
}
//group样式去掉header粘性
override init(style: UITableViewStyle) {
super.init(style: UITableViewStyle.Grouped)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - 懒加载
private lazy var label: UILabel = {
let label = UILabel()
label.textColor = UIColor.orangeColor()
label.textAlignment = NSTextAlignment.Center
label.text = "退出当前账号"
return label
}()
}
extension SetupViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
} else if section == 1 || section == 2 {
return 3
} else {
return 1
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 4
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
if indexPath.section == 0 {
cell.textLabel?.text = arrayTitle1[indexPath.row]
}
if indexPath.section == 1 {
cell.textLabel?.text = arrayTitle2[indexPath.row]
}
if indexPath.section == 2 {
cell.textLabel?.text = arrayTitle3[indexPath.row]
}
if indexPath.section == 3 {
cell.accessoryType = UITableViewCellAccessoryType.None
cell.contentView.addSubview(label)
label.Fill(cell.contentView, insets: UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0))
}
return cell
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.0000000000000001
}
}
| apache-2.0 | 3f617e8c178771e6ba50e238b6dfdfe1 | 31.031915 | 118 | 0.635669 | 4.880065 | false | false | false | false |
hardikdevios/HKKit | Pod/Classes/HKSubclass/HKOperation.swift | 1 | 1560 | //
// HKoperationQueue.swift
// Genemedics
//
// Created by Plenar on 6/2/16.
// Copyright © 2016 Plenar. All rights reserved.
//
import Foundation
open class HKOperation : Operation {
public static var delegate:HKMulticastDelegate<HKQueueConfirmation> = HKMulticastDelegate<HKQueueConfirmation>()
override open var isAsynchronous: Bool {
return true
}
fileprivate var _executing: Bool = false
override open var isExecuting: Bool {
get {
return _executing
}
set {
if (_executing != newValue) {
self.willChangeValue(forKey: "isExecuting")
_executing = newValue
self.didChangeValue(forKey: "isExecuting")
}
}
}
fileprivate var _finished: Bool = false;
override open var isFinished: Bool {
get {
return _finished
}
set {
if (_finished != newValue) {
self.willChangeValue(forKey: "isFinished")
_finished = newValue
self.didChangeValue(forKey: "isFinished")
}
}
}
open func completeOperation() {
isExecuting = false
isFinished = true
HKOperation.delegate.invoke { (queue) in
queue.completed(operation: self)
}
}
override open func start() {
if (isCancelled) {
isFinished = true
return
}
isExecuting = true
main()
}
}
| mit | 97646b635f1fb3e18ec5ac36815fe943 | 22.984615 | 117 | 0.5356 | 5.094771 | false | false | false | false |
Trxy/TRX | Readme.playground/Contents.swift | 1 | 1431 | import TRX
import UIKit
struct ExampleObject {
var value: Double
}
var object = ExampleObject(value: 0)
var anOtherObject = object
struct ExampleLayer {
var position: CGPoint
}
var layer = ExampleLayer(position: CGPoint.zero)
var myView = UIView()
var someFrame = CGRect()
Tween(from: 0, to: 20, time: 0.3) {
object.value = $0
}.start()
1.trx(to: 20) { object.value = $0 }.start()
Tween(from: CGPoint.zero, to: CGPoint(x: 20, y: 15), time: 0.3) {
layer.position = $0
}.start()
Tween(from: 0,
to: 1,
time: 0.3,
delay: 0.1,
ease: Ease.Elastic.easeOut,
key: "MyOwnKey",
onStart: { print("start") },
onComplete: { done in print("complete and done: \(done)") }) { value in
object.value = value
}.start()
TimeLine(tweens: [
1.trx(to: 20) { object.value = $0 },
30.trx(to: 40) { object.value = $0 },
40.trx(to: 50) { object.value = $0 },
]).start()
let timeline: TimeLine = [
1.trx(to: 20) { object.value = $0 }: 0,
30.trx(to: 40) { anOtherObject.value = $0 }: -0.5,
40.trx(to: 50) { anOtherObject.value = $0 }: -0.5
]
timeline.start()
let tween = Tween(from: 0,
to: 1,
time: 0.5) { print($0) }
tween.scale = 2 // duration: 1s
tween.duration = 2.0 // scale: 4
myView.trxCenter(to: CGPoint(x: 10, y: 15))
myView.trxCenter(from: CGPoint.zero)
myView.trxFrame(to: someFrame)
myView.trxFrame(to: someFrame)
| mit | 87c90bf1fe87899e29b28e88ed587c7f | 20.358209 | 77 | 0.598183 | 2.773256 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio | uoregon-cis-399/assignment1/Assignment1.playground/Pages/ParticipantProtocolAndExtension.xcplaygroundpage/Contents.swift | 1 | 3704 | /*:
[Previous](@previous)
# Participant protocol and extension
### Participant protocol
This work should be done in the Participant.swift file that already exists in the project.
The `Participant` protocol defines a set of methods and properties that must be implemented by a type in order to be a `Participant` in a `TriathlonEvent`.
1. The `Participant` protocol should require an initializer that takes a single parameter with the label `name` of type `String`.
2. The `Participant` protocol should require a method named `completionTime` that takes a first parameter with the label `for` of type `Sport`, a second parameter with the label `in` of type `Triathlon`, a third parameter with the label `randomValue` of type `Double`, and returns a value of type `Int`. Note that the `randomValue` parameter will be used by the unit tests in the project to pass known values which will remove the randomization during testing.
3. The `Participant` protocol should require a variable named `name` of type `String` that provides at least a `get` implementation.
4. The `Participant` protocol should require a variable named `favoriteSport` of the optional type `Sport?` that provides a `get` implementation.
### Extension of Participant
The extension to the `Participant` protocol defines default functionality that will be added to any type conforming to the `Participant` protocol if that type does not provide its own implementation. Add your implementation of the extension to the `Participant` protocol below your `Participant` protocol implementation in the same file.
1. The extension will add a method not declared in the `Participant` protocol that can be used to get the participants speed for a given sport. This method should be named `metersPerMinute`, take a first parameter with the label `for` of type `Sport`, a second parameter with the label `randomValue` of type `Double` which has a default value of `Double.random()`, and return a value of type `Int`.
The body of this method should use the following logic:
var value: Double
switch sport {
case .swimming:
value = 43
case .cycling:
value = 500
case .running:
value = 157
}
var modifier = 0.85 + (randomValue * 0.3)
if let favoriteSport = self.favoriteSport {
if favoriteSport == sport {
modifier += 0.05
}
else {
modifier -= 0.1
}
}
return Int(value * modifier)
2. The extension will provide a variation of the `completionTime(for:in:randomValue:)` function without the third parameter for convenience. Add a method with the name `completionTime` that takes a first parameter with the label `for` of type `Sport`, a second parameter with the label `in` of type `Triathlon`, and returns a value of type `Int`. The implementation of this method should return the result of calling the version of the method that takes all three parameters, passing through the two parameters it was invoked with for the first two parameters and `Double.random()` for the third parameter.
3. The extensions will also provide a default implementation of the `completionTime(for:in:randomValue:)` function as declared in the `Participant` protocol. The implementation of this method should call the `distance(for:)` method on the received `Triathlon` instance passing through the received `Sport` instance as the parameter value and store the result in a constant. It should then call the `metersPerMinute(for:randomValue:)` method passing through the received `Sport` and `Double` instances and store the result in a constant. Finally it should return the result of dividing the first stored value by the second stored value.
The next page will describe how to [implement the Athlete class](@next).
*/
| gpl-3.0 | db0c67594fe94abf0b76a9c6bcf95df2 | 70.230769 | 638 | 0.771598 | 4.332164 | false | false | false | false |
gutsandglory/SmullyanPredicateLogic | SmullyanPredicateLogic/PuzzleBook.swift | 1 | 10880 | //
// PuzzleBook.swift
// SmullyanPredicateLogic
//
// Created by Søren Lind Kristiansen on 15/05/15.
// Copyright (c) 2015 Guts & Glory ApS. All rights reserved.
//
import Foundation
/// An implementation of a few of the puzzles from Smullyan's book, The Riddle of Scheherazade.
class PuzzleBook: NSObject {
class func puzzle76() {
let agentNameA = "Bahman"
let agentNameB = "Perviz"
let married = "Married"
var puzzle = Puzzle.puzzleWithAgentNames([agentNameA, agentNameB], predicates: [married])
println("Initial Puzzle State:")
println(puzzle)
// Add knowledge that A and B are of the same family.
let expATruthTeller = PredicateLogic.predicateForAgent(agentNameA, predicateName: Agent.truthTellerFamily)
let expBTruthTeller = PredicateLogic.predicateForAgent(agentNameB, predicateName: Agent.truthTellerFamily)
let expSameFamily = PredicateLogic.biConditionalWithAntecedent(expATruthTeller, consequent: expBTruthTeller)
puzzle.applyExpressionFilter(expSameFamily)
// Add knowledge that A says A and B are married.
let expMarriedA = PredicateLogic.predicateForAgent(agentNameA, predicateName: married)
let expMarriedB = PredicateLogic.predicateForAgent(agentNameB, predicateName: married)
let expMarriedAandB = PredicateLogic.conjunctionWithLeftConjunct(expMarriedA, rightConjunct: expMarriedB)
puzzle.applyQuestionFilter(expMarriedAandB, agentName: agentNameA)
// Add knowledige that B says he is not married.
let expNotMarriedB = PredicateLogic.negationWithOperand(expMarriedB)
puzzle.applyQuestionFilter(expNotMarriedB, agentName: agentNameB)
println("State After Solving The Puzzle:")
println(puzzle)
}
class func puzzle77() {
let agentNameA = "Bahman"
let agentNameB = "Perviz"
let married = "Married"
var puzzle = Puzzle.puzzleWithAgentNames([agentNameA, agentNameB], predicates: [married])
// Add knowledge that A and B are of the same family.
let expATruthTeller = PredicateLogic.predicateForAgent(agentNameA, predicateName: Agent.truthTellerFamily)
let expBTruthTeller = PredicateLogic.predicateForAgent(agentNameB, predicateName: Agent.truthTellerFamily)
let expSameFamily = PredicateLogic.biConditionalWithAntecedent(expATruthTeller, consequent: expBTruthTeller)
puzzle.applyExpressionFilter(expSameFamily)
// Add knowledge that A says A and B are both married or they are both unmarried. That is, they have same marital status.
let expMarriedA = PredicateLogic.predicateForAgent(agentNameA, predicateName: married)
let expMarriedB = PredicateLogic.predicateForAgent(agentNameB, predicateName: married)
let expSameMaritalStatus = PredicateLogic.biConditionalWithAntecedent(expMarriedA, consequent: expMarriedB)
puzzle.applyQuestionFilter(expSameMaritalStatus, agentName: agentNameA)
// Add knowledige that B says he is not married.
let expNotMarriedB = PredicateLogic.negationWithOperand(expMarriedB)
puzzle.applyQuestionFilter(expNotMarriedB, agentName: agentNameB)
println(puzzle)
}
class func puzzle78() {
let agentNameA = "Bahman"
let agentNameB = "Perviz"
let married = "Married"
var puzzle = Puzzle.puzzleWithAgentNames([agentNameA, agentNameB], predicates: [married])
println("Initial Puzzle State:")
println(puzzle)
// Add knowledge that A and B are of the same family.
let expATruthTeller = PredicateLogic.predicateForAgent(agentNameA, predicateName: Agent.truthTellerFamily)
let expBTruthTeller = PredicateLogic.predicateForAgent(agentNameB, predicateName: Agent.truthTellerFamily)
let expSameFamily = PredicateLogic.biConditionalWithAntecedent(expATruthTeller, consequent: expBTruthTeller)
puzzle.applyExpressionFilter(expSameFamily)
// Add knowledge that at least one of the two are married.
let expMarriedA = PredicateLogic.predicateForAgent(agentNameA, predicateName: married)
let expMarriedB = PredicateLogic.predicateForAgent(agentNameB, predicateName: married)
let expMarriedAOrB = PredicateLogic.disjunctionWithLeftDisjunct(expMarriedA, rightDisjunct: expMarriedB)
puzzle.applyQuestionFilter(expMarriedAOrB, agentName: agentNameA)
// Add knowledige that B says he is married or he said that he was not married and
// that this leads the investigator to deduce the marital status of both A and B.
let expNotMarriedB = PredicateLogic.negationWithOperand(expMarriedB)
puzzle.applyMetaPuzzleFilterStatements([expMarriedB, expNotMarriedB], agentName: agentNameB, checkExpressions: [expMarriedA, expMarriedB])
println("State After Solving The Puzzle:")
println(puzzle)
let expBSaysMarriedB = PredicateLogic.questionToAgentWithName(agentNameB, question: expMarriedB)
let deducedAnswer = puzzle.query(expBSaysMarriedB)
let deducedAnswerText = (deducedAnswer! ? "" : "Not ") + married
println("(\(agentNameB) said he was \(deducedAnswerText))")
}
class func puzzle80() {
let agentNameA = "Agent A"
let agentNameB = "Agent B"
let agentNameC = "Agent C"
let towncrier = "TownCrier"
var puzzle = Puzzle.puzzleWithAgentNames([agentNameA, agentNameB, agentNameC], predicates: [towncrier])
println("Initial Puzzle State:")
println(puzzle)
let x = "x"
let y = "y"
// Add knowledge that there is exactly one towncrier
let exactlyOneTowncrier = PredicateLogic.exactlyOneAgentHasPredicate(towncrier)
puzzle.applyExpressionFilter(exactlyOneTowncrier)
// A says he is not the towncrier
let expTowncrierA = PredicateLogic.predicateForAgent(agentNameA, predicateName: towncrier)
let expNotTowncrierA = PredicateLogic.negationWithOperand(expTowncrierA)
puzzle.applyQuestionFilter(expNotTowncrierA, agentName: agentNameA)
// B says the town crier is a liar
let expXIsTruthteller = PredicateLogic.predicateForVariable(x, predicateName: Agent.truthTellerFamily)
let expXisLiar = PredicateLogic.negationWithOperand(expXIsTruthteller)
let expXIsTowncrier = PredicateLogic.predicateForVariable(x, predicateName: towncrier)
let expIfXTowncrierThenLiar = PredicateLogic.conditionalWithAntecedent(expXIsTowncrier, consequent: expXisLiar)
let forAllXIfXTowncrierThenLiar = PredicateLogic.forAll(x, openExpression: expIfXTowncrierThenLiar)
puzzle.applyQuestionFilter(forAllXIfXTowncrierThenLiar, agentName: agentNameB)
// C says A, B and C are liars
let forAllX_XIsLiar = PredicateLogic.forAll(x, openExpression: expXisLiar)
puzzle.applyQuestionFilter(forAllX_XIsLiar, agentName: agentNameC)
println("State After Solving The Puzzle:")
println(puzzle)
if let theTownCrierIsALiar = puzzle.query(forAllXIfXTowncrierThenLiar) {
let text = theTownCrierIsALiar ? Agent.liarFamily : Agent.truthTellerFamily
println("The town crier is a \(text).")
}
else {
println("Its unknown whether the town crier is " +
"\(Agent.truthTellerFamily) or \(Agent.liarFamily).")
}
}
class func puzzle81() {
let agentNameA = "Agent A"
let agentNameB = "Agent B"
let agentNameC = "Agent C"
let towncrier = "TownCrier"
var puzzle = Puzzle.puzzleWithAgentNames([agentNameA, agentNameB, agentNameC], predicates: [towncrier])
println("Initial Puzzle State:")
println(puzzle)
let x = "x"
let y = "y"
// Add knowledge that there is exactly one towncrier
let exactlyOneTowncrier = PredicateLogic.exactlyOneAgentHasPredicate(towncrier)
puzzle.applyExpressionFilter(exactlyOneTowncrier)
// A says he is not the towncrier
let expTowncrierA = PredicateLogic.predicateForAgent(agentNameA, predicateName: towncrier)
let expNotTowncrierA = PredicateLogic.negationWithOperand(expTowncrierA)
puzzle.applyQuestionFilter(expNotTowncrierA, agentName: agentNameA)
// B says the town crier is a liar
let expXIsTruthteller = PredicateLogic.predicateForVariable(x, predicateName: Agent.truthTellerFamily)
let expXisLiar = PredicateLogic.negationWithOperand(expXIsTruthteller)
let expXIsTowncrier = PredicateLogic.predicateForVariable(x, predicateName: towncrier)
let expIfXTowncrierThenLiar = PredicateLogic.conditionalWithAntecedent(expXIsTowncrier, consequent: expXisLiar)
let forAllXIfXTowncrierThenLiar = PredicateLogic.forAll(x, openExpression: expIfXTowncrierThenLiar)
puzzle.applyQuestionFilter(forAllXIfXTowncrierThenLiar, agentName: agentNameB)
// C says A, B and C are liars
let forAllX_XIsLiar = PredicateLogic.forAll(x, openExpression: expXisLiar)
puzzle.applyQuestionFilter(forAllX_XIsLiar, agentName: agentNameC)
// A says C is a liar
let expCIsTruthTeller = PredicateLogic.predicateForAgent(agentNameC, predicateName: Agent.truthTellerFamily)
let expCIsLiar = PredicateLogic.negationWithOperand(expCIsTruthTeller)
puzzle.applyQuestionFilter(expCIsLiar, agentName: agentNameA)
println("State After Solving The Puzzle:")
println(puzzle)
}
class func puzzle82() {
let agentNameA = "Agent A"
let agentNameB = "Agent B"
let agentNameC = "Agent C"
var puzzle = Puzzle.puzzleWithAgentNames([agentNameA, agentNameB, agentNameC], predicates: [])
println("Initial Puzzle State:")
println(puzzle)
let exactlyTwoAreTruthtellers = PredicateLogic.exactlyNAgentsHavePredicate(Agent.truthTellerFamily, n: 2)
puzzle.applyQuestionFilter(exactlyTwoAreTruthtellers, agentName: agentNameA)
let exactlyOneIsTruthteller = PredicateLogic.exactlyNAgentsHavePredicate(Agent.truthTellerFamily, n: 1)
puzzle.applyQuestionFilter(exactlyOneIsTruthteller, agentName: agentNameB)
puzzle.applyQuestionFilter(exactlyOneIsTruthteller, agentName: agentNameC)
println("State After Solving The Puzzle:")
println(puzzle)
}
}
| mit | 557a15b4f4008628b23c76dc2cab328b | 47.137168 | 146 | 0.694181 | 4.13493 | false | false | false | false |
automagicly/IphoneIpadProgramming | iCuisine/iCuisine/Recipe.swift | 1 | 2126 | //
// File.swift
// iCuisine
//
// Created by William Dalmorra De Souza on 4/3/15.
// Copyright (c) 2015 Golden Avocado Labs. All rights reserved.
//
import Foundation
import UIKit
class Static {
struct Favorites {
static var favoritesArray = [Recipe]()
}
}
@objc(Recipe)
class Recipe : NSObject, NSCoding{
var name: String!;
var ingredients: [String]!;
var image: String!;
var recipeDescription: String!;
var isFav: Bool! = false
init(name: String, ingredients: [String], description: String, image: String ){
self.name = name
self.ingredients = ingredients
self.image = image
self.recipeDescription = description
}
required init (coder aDecoder: NSCoder){
if let rName = aDecoder.decodeObjectForKey("name") as? String {
self.name = rName
}
if let rIng = aDecoder.decodeObjectForKey("ingredients") as? [String] {
self.ingredients = rIng
}
if let rIma = aDecoder.decodeObjectForKey("image") as? String {
self.image = rIma
}
if let rDesc = aDecoder.decodeObjectForKey("recipeDescription") as? String {
self.recipeDescription = rDesc
}
if let risF = aDecoder.decodeObjectForKey("isFav") as? Bool {
self.isFav = risF
}
}
func encodeWithCoder(aCoder: NSCoder) {
if let rName = self.name {
aCoder.encodeObject(rName, forKey: "name")
}
if let rIng = self.ingredients {
aCoder.encodeObject(rIng, forKey: "ingredients")
}
if let rIma = self.image {
aCoder.encodeObject(rIma, forKey: "image")
}
if let rDesc = self.recipeDescription {
aCoder.encodeObject(rDesc, forKey: "recipeDescription")
}
if let risF = self.isFav {
aCoder.encodeObject(risF, forKey: "isFav")
}
}
func equals(r: Recipe) -> Bool{
if (r.name == self.name) {
return true
} else {
return false
}
}
} | mit | 4fe82c82f586d3cdaccad23ef2bfae43 | 25.924051 | 84 | 0.570555 | 4.168627 | false | false | false | false |
MessageKit/MessageKit | Sources/Models/MessageStyle.swift | 1 | 4334 | // MIT License
//
// Copyright (c) 2017-2019 MessageKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public enum MessageStyle {
// MARK: - MessageStyle
case none
case bubble
case bubbleOutline(UIColor)
case bubbleTail(TailCorner, TailStyle)
case bubbleTailOutline(UIColor, TailCorner, TailStyle)
case custom((MessageContainerView) -> Void)
// MARK: Public
// MARK: - TailCorner
public enum TailCorner: String {
case topLeft
case bottomLeft
case topRight
case bottomRight
internal var imageOrientation: UIImage.Orientation {
switch self {
case .bottomRight: return .up
case .bottomLeft: return .upMirrored
case .topLeft: return .down
case .topRight: return .downMirrored
}
}
}
// MARK: - TailStyle
public enum TailStyle {
case curved
case pointedEdge
internal var imageNameSuffix: String {
switch self {
case .curved:
return "_tail_v2"
case .pointedEdge:
return "_tail_v1"
}
}
}
public var image: UIImage? {
if
let imageCacheKey = imageCacheKey,
let cachedImage = MessageStyle.bubbleImageCache.object(forKey: imageCacheKey as NSString)
{
return cachedImage
}
guard
let imageName = imageName,
var image = UIImage(named: imageName, in: Bundle.messageKitAssetBundle, compatibleWith: nil)
else {
return nil
}
switch self {
case .none, .custom:
return nil
case .bubble, .bubbleOutline:
break
case .bubbleTail(let corner, _), .bubbleTailOutline(_, let corner, _):
guard let cgImage = image.cgImage else { return nil }
image = UIImage(cgImage: cgImage, scale: image.scale, orientation: corner.imageOrientation)
}
let stretchedImage = stretch(image)
if let imageCacheKey = imageCacheKey {
MessageStyle.bubbleImageCache.setObject(stretchedImage, forKey: imageCacheKey as NSString)
}
return stretchedImage
}
// MARK: Internal
internal static let bubbleImageCache: NSCache<NSString, UIImage> = {
let cache = NSCache<NSString, UIImage>()
cache.name = "com.messagekit.MessageKit.bubbleImageCache"
return cache
}()
// MARK: Private
private var imageCacheKey: String? {
guard let imageName = imageName else { return nil }
switch self {
case .bubble, .bubbleOutline:
return imageName
case .bubbleTail(let corner, _), .bubbleTailOutline(_, let corner, _):
return imageName + "_" + corner.rawValue
default:
return nil
}
}
private var imageName: String? {
switch self {
case .bubble:
return "bubble_full"
case .bubbleOutline:
return "bubble_outlined"
case .bubbleTail(_, let tailStyle):
return "bubble_full" + tailStyle.imageNameSuffix
case .bubbleTailOutline(_, _, let tailStyle):
return "bubble_outlined" + tailStyle.imageNameSuffix
case .none, .custom:
return nil
}
}
private func stretch(_ image: UIImage) -> UIImage {
let center = CGPoint(x: image.size.width / 2, y: image.size.height / 2)
let capInsets = UIEdgeInsets(top: center.y, left: center.x, bottom: center.y, right: center.x)
return image.resizableImage(withCapInsets: capInsets, resizingMode: .stretch)
}
}
| mit | 99fab7c92046e481c4946ae1c3585191 | 28.684932 | 98 | 0.68874 | 4.413442 | false | false | false | false |
sebarina/BCWeekTimeTable | BCTimeTableDemo/BCTimeTableDemo/ViewController.swift | 1 | 7471 | //
// ViewController.swift
// BCTimeTableDemo
//
// Created by Sebarina Xu on 6/10/16.
// Copyright © 2016 bocai. All rights reserved.
//
import UIKit
import BCWeekTimeTable
class ViewController: UIViewController {
@IBAction func popover(sender: UIButton) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("popover")
vc.modalPresentationStyle = .Popover
vc.preferredContentSize = CGSizeMake(200, 180)
if let popVC = vc.popoverPresentationController {
popVC.sourceView = sender
popVC.sourceRect.origin.y += sender.frame.height
popVC.sourceRect.origin.x += sender.frame.width/2
popVC.delegate = self
}
presentViewController(vc, animated: true, completion: nil)
}
@IBOutlet weak var actionButton: UIButton!
var weekTableView : WeekTimeTableView?
private let queue = dispatch_queue_create("com.aschuch.cache.diskQueue", DISPATCH_QUEUE_CONCURRENT)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let ap = calendarAppearance()
ap.firstDay = .Sunday
weekTableView = WeekTimeTableView(frame: CGRectZero, appearance: ap)
view.insertSubview(weekTableView!, atIndex: 0)
weekTableView?.translatesAutoresizingMaskIntoConstraints = false
let constraints1 = NSLayoutConstraint(item: weekTableView!, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: .Leading, multiplier: 1, constant: 0)
let constraints2 = NSLayoutConstraint(item: weekTableView!, attribute: .Trailing, relatedBy: .Equal, toItem: self.view, attribute: .Trailing, multiplier: 1, constant: 0)
let constraints3 = NSLayoutConstraint(item: weekTableView!, attribute: .Top, relatedBy: .Equal, toItem: self.topLayoutGuide, attribute: .Bottom, multiplier: 1, constant: 0)
let constraints4 = NSLayoutConstraint(item: weekTableView!, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([constraints1, constraints2, constraints3, constraints4])
//
weekTableView?.weekTimeAppearanceDelegate = self
weekTableView?.weekTimeDelegate = self
let format = NSDateFormatter()
format.dateFormat = "yyyy-MM-dd HH:mm"
format.timeZone = NSTimeZone.localTimeZone()
let event1 = WeekScheduleEvent(startDate: NSDate(), endDate: NSDate().dateByAddingTimeInterval(3600), eventColor: UIColor.blueColor().colorWithAlphaComponent(0.6), eventTitle: "测试事件", customValue: Reservation())
let event2 = WeekScheduleEvent(startDate: NSDate().dateByAddingTimeInterval(-7200), endDate: NSDate().dateByAddingTimeInterval(-3600), eventColor: UIColor.greenColor().colorWithAlphaComponent(0.6), eventTitle: "测试事件1", customValue: Reservation())
let event3 = WeekScheduleEvent(startDate: NSDate().dateByAddingTimeInterval(-1800), endDate: NSDate().dateByAddingTimeInterval(1800), eventColor: UIColor.orangeColor().colorWithAlphaComponent(0.6), eventTitle: "测试事件2", customValue: Reservation())
let event4 = WeekScheduleEvent(startDate: NSDate().dateByAddingTimeInterval(-3600*2.5), endDate: NSDate().dateByAddingTimeInterval(-3600*1.5), eventColor: UIColor.redColor().colorWithAlphaComponent(0.6), eventTitle: "测试事件3", customValue: Reservation())
let event5 = WeekScheduleEvent(startDate: format.dateFromString("2016-6-15 08:00")!, endDate: format.dateFromString("2015-6-15 09:00")!, eventColor: UIColor.blueColor().colorWithAlphaComponent(0.6), eventTitle: "测试事件5", customValue: nil)
let event6 = WeekScheduleEvent(startDate: format.dateFromString("2016-6-13 21:00")!, endDate: format.dateFromString("2015-6-13 22:00")!, eventColor: UIColor.blueColor().colorWithAlphaComponent(0.6), eventTitle: "测试事件6", customValue: nil)
let event7 = WeekScheduleEvent(startDate: format.dateFromString("2016-6-15 07:00")!, endDate: format.dateFromString("2015-6-15 09:00")!, eventColor: UIColor.blueColor().colorWithAlphaComponent(0.6), eventTitle: "测试事件7", customValue: nil)
let event8 = WeekScheduleEvent(startDate: format.dateFromString("2016-6-13 21:00")!, endDate: format.dateFromString("2015-6-13 23:00")!, eventColor: UIColor.blueColor().colorWithAlphaComponent(0.6), eventTitle: "测试事件8", customValue: nil)
weekTableView?.events = [event1, event2, event3, event4, event5, event6, event7, event8]
}
}
extension ViewController : WeekTimeTableDelegate {
func weekTimeTableAddEvent(starTime: NSDate, endTime: NSDate, addButton: UIButton) {
let format = NSDateFormatter()
format.dateFormat = "yyyy-MM-dd HH:mm"
format.timeZone = NSTimeZone.localTimeZone()
print("start time: " + format.stringFromDate(starTime))
print("end time: " + format.stringFromDate(endTime))
}
func weekTimeTableDidSelectEvent(event: AnyObject?) {
var test = "just for testing"
dispatch_sync(queue) {
sleep(5)
test = "just after update"
}
print(test)
}
func weekTimeWeekTimeUpdated(starTime: NSDate) {
let format = NSDateFormatter()
format.dateFormat = "yyyy-MM-dd HH:mm"
format.timeZone = NSTimeZone.localTimeZone()
print("start time: " + format.stringFromDate(weekTableView!.startTime))
print("end time: " + format.stringFromDate(weekTableView!.endTime))
}
}
extension ViewController {
func calendarAppearance() -> BCCalendarViewAppearance {
let appearance = BCCalendarViewAppearance()
appearance.currentDayTextColor = UIColor.brownColor()
appearance.currentDaySelectedBgColor = UIColor.greenColor()
appearance.currentDayBgColor = UIColor.whiteColor()
appearance.weekDaySelectedBgColor = UIColor.greenColor()
return appearance
}
}
extension ViewController : WeekTimeAppearanceDelegate {
func weekTimeAddButtonTitle() -> String {
return "+"
}
func weekTimeAddButtonBgColor() -> UIColor {
return UIColor.brownColor()
}
func weekTimeTableDashlineColor() -> UIColor {
return UIColor.purpleColor()
}
func weekTimeTableStartHour() -> Int {
return 8
}
func weekTimeTableEndHour() -> Int {
return 22
}
}
extension ViewController : UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
}
class Reservation {
var id = ""
var courseId = ""
var courseName = ""
var traineeId = ""
var traineeName = ""
var date = ""
var startTime = ""
var duration = 0
var createType = ""
var pictures = [""]
var status = 1
var statusStr = ""
var remindTypeStr = ""
var remindType = ""
var remindIdentity = ""
var eventType = ""
var eventTypeStr = ""
var endTime = ""
var comment = ""
init() {}
}
| mit | e836df335dc9e3cf5259fbeeca0f636f | 41.079545 | 260 | 0.678234 | 4.702222 | false | false | false | false |
mohssenfathi/MTLImage | MTLImage/Sources/Core/Property.swift | 1 | 2075 | //
// Property.swift
// Pods
//
// Created by Mohssen Fathi on 4/1/16.
//
//
import UIKit
public
class Property: NSObject, NSCoding {
public
enum PropertyType: Int {
case value = 0,
bool,
point,
rect,
color,
selection,
image
}
public var title: String!
public var key: String!
// public var keyPath: AnyKeyPath!
public var propertyType: PropertyType!
public var minimumValue: Float = 0.0
public var defaultValue: Float = 0.5
public var maximumValue: Float = 1.0
public var selectionItems: [Int : String]?
init(key: String, title: String) {
super.init()
self.key = key
self.title = title
self.propertyType = .value
}
init(key: String, title: String, propertyType: PropertyType) {
super.init()
self.key = key
self.title = title
self.propertyType = propertyType
}
// MARK: - NSCoding
public func encode(with aCoder: NSCoder) {
aCoder.encode(title , forKey: "title")
aCoder.encode(key, forKey: "key")
aCoder.encode(minimumValue, forKey: "minimumValue")
aCoder.encode(maximumValue, forKey: "maximumValue")
aCoder.encode(defaultValue, forKey: "defaultValue")
aCoder.encode(selectionItems, forKey: "selectionItems")
aCoder.encode(propertyType.rawValue, forKey: "propertType")
}
required public init?(coder aDecoder: NSCoder) {
super.init()
key = aDecoder.decodeObject(forKey: "key") as! String
title = aDecoder.decodeObject(forKey: "title") as! String
minimumValue = aDecoder.decodeFloat(forKey: "minimumValue")
maximumValue = aDecoder.decodeFloat(forKey: "maximumValue")
defaultValue = aDecoder.decodeFloat(forKey: "defaultValue")
selectionItems = aDecoder.decodeObject(forKey: "selectionItems") as? [Int: String]
propertyType = PropertyType(rawValue: aDecoder.decodeInteger(forKey: "propertyType"))
}
}
| mit | adc97cdab9c411669638fc09199f7913 | 27.424658 | 93 | 0.621205 | 4.443255 | false | false | false | false |
humeng12/DouYuZB | DouYuZB/DouYuZB/Classes/Tools/Extensions/UIBarButtonItem+Extension.swift | 1 | 1311 | //
// UIBarButtonItem+Extension.swift
// DouYuZB
//
// Created by 胡猛 on 16/11/6.
// Copyright © 2016年 HuMeng. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
//加class扩展类方法
class func createItem(_ imageName:String,highImageName:String,size:CGSize) -> UIBarButtonItem{
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: UIControlState())
btn.setImage(UIImage(named: highImageName), for: .highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size: size)
return UIBarButtonItem(customView: btn)
}
//便利构造函数 1 convenience开头 2 在构造函数中必须明确调用一个设计的构造函数(self调用)
convenience init(imageName: String,highImageName: String = "",size: CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: UIControlState())
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), for: .highlighted)
}
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView:btn)
}
}
| mit | b4f157864bfa2cb1aad5f7911630294d | 26.954545 | 98 | 0.6 | 4.392857 | false | false | false | false |
ahoppen/swift | test/expr/cast/array_downcast.swift | 39 | 1586 | // RUN: %target-typecheck-verify-swift
// FIXME: Should go into the standard library.
public extension _ObjectiveCBridgeable {
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self {
var result: Self?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
class V {}
class U : V {}
class T : U {}
var v = V()
var u = U()
var t = T()
var va = [v]
var ua = [u]
var ta = [t]
va = ta
var va2: ([V])? = va as [V]
var v2: V = va2![0]
var ua2: ([U])? = va as? [U]
var u2: U = ua2![0]
var ta2: ([T])? = va as? [T]
var t2: T = ta2![0]
// Check downcasts that require bridging.
class A {
var x = 0
}
struct B : _ObjectiveCBridgeable {
func _bridgeToObjectiveC() -> A {
return A()
}
static func _forceBridgeFromObjectiveC(
_ x: A,
result: inout B?
) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: A,
result: inout B?
) -> Bool {
return true
}
}
func testBridgedDowncastAnyObject(_ arr: [AnyObject], arrOpt: [AnyObject]?,
arrIUO: [AnyObject]!) {
var b = B()
if let bArr = arr as? [B] {
b = bArr[0]
}
if let bArr = arrOpt as? [B] {
b = bArr[0]
}
if let bArr = arrIUO as? [B] {
b = bArr[0]
}
_ = b
}
func testBridgedIsAnyObject(_ arr: [AnyObject], arrOpt: [AnyObject]?,
arrIUO: [AnyObject]!) -> Bool {
let b = B()
if arr is [B] { return arr is [B] }
if arrOpt is [B] { return arrOpt is [B] }
if arrIUO is [B] { return arrIUO is [B] }
_ = b
return false
}
| apache-2.0 | b563bbeff2cad4723e64930399f4966e | 17.229885 | 78 | 0.56116 | 3.079612 | false | false | false | false |
anhnc55/fantastic-swift-library | Example/Pods/paper-onboarding/Source/PageView/Item/PageViewItem.swift | 1 | 4979 | //
// PageViewItem.swift
// AnimatedPageView
//
// Created by Alex K. on 12/04/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
class PageViewItem: UIView {
let circleRadius: CGFloat
let selectedCircleRadius: CGFloat
let lineWidth: CGFloat
let borderColor: UIColor
var select: Bool
var centerView: UIView?
var imageView: UIImageView?
var circleLayer: CAShapeLayer?
var tickIndex: Int = 0
init(radius: CGFloat, selectedRadius: CGFloat, borderColor: UIColor = .whiteColor(), lineWidth: CGFloat = 3, isSelect: Bool = false) {
self.borderColor = borderColor
self.lineWidth = lineWidth
self.circleRadius = radius
self.selectedCircleRadius = selectedRadius
self.select = isSelect
super.init(frame: CGRect.zero)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: public
extension PageViewItem {
func animationSelected(selected: Bool, duration: Double, fillColor: Bool) {
let toAlpha: CGFloat = selected == true ? 1 : 0
imageAlphaAnimation(toAlpha, duration: duration)
let currentRadius = selected == true ? selectedCircleRadius : circleRadius
let scaleAnimation = circleScaleAnimation(currentRadius - lineWidth / 2.0, duration: duration)
let toColor = fillColor == true ? UIColor.whiteColor() : UIColor.clearColor()
let colorAnimation = circleBackgroundAnimation(toColor, duration: duration)
circleLayer?.addAnimation(scaleAnimation, forKey: nil)
circleLayer?.addAnimation(colorAnimation, forKey: nil)
}
}
// MARK: configuration
extension PageViewItem {
private func commonInit() {
centerView = createBorderView()
imageView = createImageView()
}
private func createBorderView() -> UIView {
let view = Init(UIView(frame:CGRect.zero)) {
$0.backgroundColor = .blueColor()
$0.translatesAutoresizingMaskIntoConstraints = false
}
addSubview(view)
// create circle layer
let currentRadius = select == true ? selectedCircleRadius : circleRadius
let circleLayer = createCircleLayer(currentRadius, lineWidth: lineWidth)
view.layer.addSublayer(circleLayer)
self.circleLayer = circleLayer
// add constraints
[NSLayoutAttribute.CenterX, NSLayoutAttribute.CenterY].forEach { attribute in
(self , view) >>>- {
$0.attribute = attribute
}
}
[NSLayoutAttribute.Height, NSLayoutAttribute.Width].forEach { attribute in
view >>>- {
$0.attribute = attribute
}
}
return view
}
private func createCircleLayer(radius: CGFloat, lineWidth: CGFloat) -> CAShapeLayer {
let path = UIBezierPath(arcCenter: CGPoint.zero, radius: radius - lineWidth / 2.0, startAngle: 0, endAngle: CGFloat(2.0 * M_PI), clockwise: true)
let layer = Init(CAShapeLayer()) {
$0.path = path.CGPath
$0.lineWidth = lineWidth
$0.strokeColor = UIColor.whiteColor().CGColor
$0.fillColor = UIColor.clearColor().CGColor
}
return layer
}
private func createImageView() -> UIImageView {
let imageView = Init(UIImageView(frame: CGRect.zero)) {
$0.contentMode = .ScaleAspectFit
$0.translatesAutoresizingMaskIntoConstraints = false
$0.alpha = select == true ? 1 : 0
}
addSubview(imageView)
// add constraints
[NSLayoutAttribute.Left, NSLayoutAttribute.Right, NSLayoutAttribute.Top, NSLayoutAttribute.Bottom].forEach { attribute in
(self , imageView) >>>- { $0.attribute = attribute }
}
return imageView
}
}
// MARK: animations
extension PageViewItem {
private func circleScaleAnimation(toRadius: CGFloat, duration: Double) -> CABasicAnimation {
let path = UIBezierPath(arcCenter: CGPoint.zero, radius: toRadius, startAngle: 0, endAngle: CGFloat(2.0 * M_PI), clockwise: true)
let animation = Init(CABasicAnimation(keyPath: "path")) {
$0.duration = duration
$0.toValue = path.CGPath
$0.removedOnCompletion = false
$0.fillMode = kCAFillModeForwards
}
return animation
}
private func circleBackgroundAnimation(toColor: UIColor, duration: Double) -> CABasicAnimation {
let animation = Init(CABasicAnimation(keyPath: "fillColor")) {
$0.duration = duration
$0.toValue = toColor.CGColor
$0.removedOnCompletion = false
$0.fillMode = kCAFillModeForwards
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
return animation
}
private func imageAlphaAnimation(toValue: CGFloat, duration: Double) {
UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseInOut, animations: {
self.imageView?.alpha = toValue
}, completion: nil)
}
} | mit | 4555e1d75425bc7d83c29b26e31ce0bc | 31.542484 | 149 | 0.66593 | 4.772771 | false | false | false | false |
schibsted/layout | Layout/LayoutLoader.swift | 1 | 18689 | // Copyright © 2017 Schibsted. All rights reserved.
import Foundation
typealias LayoutLoaderCallback = (LayoutNode?, LayoutError?) -> Void
func clearLayoutLoaderCache() {
cache.removeAll()
}
// Cache for previously loaded layouts
private var cache = [URL: Layout]()
private let queue = DispatchQueue(label: "com.Layout.LayoutLoader")
private var reloadLock = 0
private extension Layout {
/// Merges the contents of the specified layout into this one
/// Will fail if the layout class is not a subclass of this one
func merged(with layout: Layout) throws -> Layout {
if let path = xmlPath {
throw LayoutError("Cannot extend \(className) template until content for \(path) has been loaded.")
}
let newClass: AnyClass = try layout.getClass()
let oldClass: AnyClass = try getClass()
guard newClass.isSubclass(of: oldClass) else {
throw LayoutError("Cannot replace \(oldClass) with \(newClass)")
}
var expressions = self.expressions
for (key, value) in layout.expressions {
expressions[key] = value
}
var parameters = self.parameters
for (key, value) in layout.parameters { // TODO: what about collisions?
parameters[key] = value
}
var macros = self.macros
for (key, value) in layout.macros { // TODO: what about collisions?
macros[key] = value
}
let result = Layout(
className: layout.className,
id: layout.id ?? id,
expressions: expressions,
parameters: parameters,
macros: macros,
children: children,
body: layout.body ?? body,
xmlPath: layout.xmlPath,
templatePath: templatePath,
childrenTagIndex: childrenTagIndex,
relativePath: layout.relativePath, // TODO: is this correct?
rootURL: rootURL
)
return insertChildren(layout.children, into: result)
}
// Insert children into hierarchy
private func insertChildren(_ children: [Layout], into layout: Layout) -> Layout {
func _insertChildren(_ children: [Layout], into layout: inout Layout) -> Bool {
if let index = layout.childrenTagIndex {
layout.children.insert(contentsOf: children, at: index)
return true
}
for (index, var child) in layout.children.enumerated() {
if _insertChildren(children, into: &child) {
layout.children[index] = child
return true
}
}
return false
}
var layout = layout
if !_insertChildren(children, into: &layout) {
layout.children += children
}
return layout
}
/// Recursively load all nested layout templates
func processTemplates(completion: @escaping (Layout?, LayoutError?) -> Void) {
var result = self
var error: LayoutError?
var requestCount = 1 // Offset to 1 initially to prevent premature completion
func didComplete() {
requestCount -= 1
if requestCount == 0 {
completion(error == nil ? result : nil, error)
}
}
for (index, child) in children.enumerated() {
requestCount += 1
child.processTemplates { layout, _error in
if _error != nil {
error = _error
} else if let layout = layout {
result.children[index] = layout
}
didComplete()
}
}
if let templatePath = templatePath {
requestCount += 1
LayoutLoader().loadLayout(
withContentsOfURL: urlFromString(templatePath, relativeTo: rootURL),
relativeTo: relativePath
) { layout, _error in
if _error != nil {
error = _error
} else if let layout = layout {
do {
result = try layout.merged(with: result)
} catch let _error {
error = LayoutError(_error)
}
}
didComplete()
}
}
didComplete()
}
}
// API for loading a layout XML file
class LayoutLoader {
private var _originalURL: URL!
private var _xmlURL: URL!
private var _projectDirectory: URL?
private var _dataTask: URLSessionDataTask?
private var _state: Any = ()
private var _constants: [String: Any] = [:]
private var _strings: [String: String]?
/// Used for protecting operations that must not be interupted by a reload.
/// Any reload attempts that happen inside the block will be ignored
static func atomic<T>(_ protected: () throws -> T) rethrows -> T {
queue.sync { reloadLock += 1 }
defer { queue.sync { reloadLock -= 1 } }
return try protected()
}
// MARK: LayoutNode loading
/// Loads a named XML layout file from the app resources folder
public func loadLayoutNode(
named: String,
bundle: Bundle = Bundle.main,
relativeTo: String = #file,
state: Any = (),
constants: [String: Any] = [:]
) throws -> LayoutNode {
_state = state
_constants = constants
let layout = try loadLayout(
named: named,
bundle: bundle,
relativeTo: relativeTo
)
return try LayoutNode(
layout: layout,
state: state,
constants: constants
)
}
/// Loads a local or remote XML layout file with the specified URL
public func loadLayoutNode(
withContentsOfURL xmlURL: URL,
relativeTo: String? = #file,
state: Any = (),
constants: [String: Any] = [:],
completion: @escaping LayoutLoaderCallback
) {
_state = state
_constants = constants
loadLayout(
withContentsOfURL: xmlURL,
relativeTo: relativeTo,
completion: { [weak self] layout, error in
self?._state = state
self?._constants = constants
do {
guard let layout = layout else {
if let error = error {
throw error
}
return
}
try completion(LayoutNode(
layout: layout,
state: state,
constants: constants
), nil)
} catch {
completion(nil, LayoutError(error))
}
}
)
}
/// Reloads the most recently loaded XML layout file
public func reloadLayoutNode(withCompletion completion: @escaping LayoutLoaderCallback) {
guard let xmlURL = _originalURL, _dataTask == nil, queue.sync(execute: {
guard reloadLock == 0 else { return false }
cache.removeAll()
return true
}) else {
completion(nil, nil)
return
}
loadLayoutNode(
withContentsOfURL: xmlURL,
relativeTo: nil,
state: _state,
constants: _constants,
completion: completion
)
}
// MARK: Layout loading
public func loadLayout(
named: String,
bundle: Bundle = Bundle.main,
relativeTo: String = #file
) throws -> Layout {
assert(Thread.isMainThread)
guard let xmlURL = bundle.url(forResource: named, withExtension: nil) ??
bundle.url(forResource: named, withExtension: "xml") else {
throw LayoutError.message("No layout XML file found for \(named)")
}
var _layout: Layout?
var _error: Error?
loadLayout(
withContentsOfURL: xmlURL,
relativeTo: relativeTo
) { layout, error in
_layout = layout
_error = error
}
if let error = _error {
throw error
}
guard let layout = _layout else {
throw LayoutError("Unable to synchronously load \(named). It may depend on a remote template. Try using loadLayout(withContentsOfURL:) instead")
}
return layout
}
public func loadLayout(
withContentsOfURL xmlURL: URL,
relativeTo: String? = #file,
completion: @escaping (Layout?, LayoutError?) -> Void
) {
_dataTask?.cancel()
_dataTask = nil
_originalURL = xmlURL.standardizedFileURL
_xmlURL = _originalURL
_strings = nil
func processLayoutData(_ data: Data) throws {
assert(Thread.isMainThread) // TODO: can we parse XML in the background instead?
do {
let layout = try Layout(xmlData: data, url: _xmlURL, relativeTo: relativeTo)
queue.async { cache[self._xmlURL] = layout }
layout.processTemplates(completion: completion)
} catch {
throw LayoutError(error, in: xmlURL.lastPathComponent)
}
}
// If it's a bundle resource url, replace with equivalent source url
if xmlURL.isFileURL {
let xmlURL = xmlURL.standardizedFileURL
let bundlePath = Bundle.main.bundleURL.absoluteString
if xmlURL.absoluteString.hasPrefix(bundlePath) {
if _projectDirectory == nil, let relativeTo = relativeTo,
let projectDirectory = findProjectDirectory(at: relativeTo) {
_projectDirectory = projectDirectory
}
if let projectDirectory = _projectDirectory {
let xmlPath = xmlURL.absoluteString
var parts = xmlPath[bundlePath.endIndex ..< xmlPath.endIndex].components(separatedBy: "/")
for (i, part) in parts.enumerated().reversed() {
if part.hasSuffix(".bundle") {
parts.removeFirst(i + 1)
break
}
}
let path = parts.joined(separator: "/")
do {
_xmlURL = try findSourceURL(forRelativePath: path, in: projectDirectory)
} catch {
completion(nil, LayoutError(error))
return
}
}
}
}
// Check cache
var layout: Layout?
queue.sync { layout = cache[_xmlURL] }
if let layout = layout {
layout.processTemplates(completion: completion)
return
}
// Load synchronously if it's a local file and we're on the main thread already
if _xmlURL.isFileURL, Thread.isMainThread {
do {
let data = try Data(contentsOf: _xmlURL)
try processLayoutData(data)
} catch {
completion(nil, LayoutError(error))
}
return
}
// Load asynchronously
let xmlURL = _xmlURL!
_dataTask = URLSession.shared.dataTask(with: xmlURL) { data, _, error in
DispatchQueue.main.async {
self._dataTask = nil
if self._xmlURL != xmlURL {
return // Must have been cancelled
}
do {
guard let data = data else {
if let error = error {
throw error
}
return
}
try processLayoutData(data)
} catch {
completion(nil, LayoutError(error))
}
}
}
_dataTask?.resume()
}
// MARK: String loading
public func loadLocalizedStrings() throws -> [String: String] {
if let strings = _strings {
return strings
}
var path = "Localizable.strings"
let localizedPath = Bundle.main.path(forResource: "Localizable", ofType: "strings")
if let resourcePath = Bundle.main.resourcePath, let localizedPath = localizedPath {
path = String(localizedPath[resourcePath.endIndex ..< localizedPath.endIndex])
}
if let projectDirectory = _projectDirectory {
let url = try findSourceURL(forRelativePath: path, in: projectDirectory)
_strings = NSDictionary(contentsOf: url) as? [String: String] ?? [:]
return _strings!
}
if let stringsFile = localizedPath {
_strings = NSDictionary(contentsOfFile: stringsFile) as? [String: String] ?? [:]
return _strings!
}
return [:]
}
// MARK: Internal APIs exposed for LayoutConsole
func setSourceURL(_ sourceURL: URL, for path: String) {
_setSourceURL(sourceURL, for: path)
}
func clearSourceURLs() {
_clearSourceURLs()
}
// MARK: Internal APIs exposed for testing
func findProjectDirectory(at path: String) -> URL? {
return _findProjectDirectory(at: path)
}
func findSourceURL(
forRelativePath path: String,
in directory: URL,
ignoring: [URL] = [],
usingCache: Bool = true
) throws -> URL {
guard let url = try _findSourceURL(
forRelativePath: path,
in: directory,
ignoring: ignoring,
usingCache: usingCache
) else {
throw LayoutError.message("Unable to locate source file for \(path)")
}
return url
}
}
#if arch(i386) || arch(x86_64)
// MARK: Only applicable when running in the simulator
private var layoutSettings: [String: Any] {
get { return UserDefaults.standard.dictionary(forKey: "com.Layout") ?? [:] }
set { UserDefaults.standard.set(newValue, forKey: "com.Layout") }
}
private var _projectDirectory: URL? {
didSet {
let path = _projectDirectory?.path
if path != layoutSettings["projectDirectory"] as? String {
sourcePaths.removeAll()
layoutSettings["projectDirectory"] = path
}
}
}
private var _sourcePaths: [String: String] = {
layoutSettings["sourcePaths"] as? [String: String] ?? [:]
}()
private var sourcePaths: [String: String] {
get { return _sourcePaths }
set {
_sourcePaths = newValue
layoutSettings["sourcePaths"] = _sourcePaths
}
}
private func _findProjectDirectory(at path: String) -> URL? {
var url = URL(fileURLWithPath: path).standardizedFileURL
if let projectDirectory = _projectDirectory,
url.absoluteString.hasPrefix(projectDirectory.absoluteString) {
return projectDirectory
}
if !url.hasDirectoryPath {
url.deleteLastPathComponent()
}
while !url.absoluteString.isEmpty {
if let files = try? FileManager.default.contentsOfDirectory(
at: url,
includingPropertiesForKeys: nil,
options: []
), files.contains(where: { ["xcodeproj", "xcworkspace"].contains($0.pathExtension) }) {
return url
}
url.deleteLastPathComponent()
}
return nil
}
private func _findSourceURL(
forRelativePath path: String,
in directory: URL,
ignoring: [URL],
usingCache: Bool
) throws -> URL? {
if let filePath = sourcePaths[path], FileManager.default.fileExists(atPath: filePath) {
let url = URL(fileURLWithPath: filePath).standardizedFileURL
if url.absoluteString.hasPrefix(directory.absoluteString) {
return url
}
}
guard let files = try? FileManager.default.contentsOfDirectory(atPath: directory.path) else {
return nil
}
var ignoring = ignoring
if files.contains(layoutIgnoreFile) {
ignoring += try LayoutError.wrap {
try parseIgnoreFile(directory.appendingPathComponent(layoutIgnoreFile))
}
}
var parts = path.components(separatedBy: "/")
if parts[0] == "" {
parts.removeFirst()
}
var results = [URL]()
for file in files where
file != "build" && !file.hasPrefix(".") && ![
".build", ".app", ".framework", ".xcodeproj", ".xcassets"
].contains(where: { file.hasSuffix($0) }) {
let directory = directory.appendingPathComponent(file)
if ignoring.contains(directory) {
continue
}
if file == parts[0] {
if parts.count == 1 {
results.append(directory) // Not actually a directory
continue
}
try _findSourceURL(
forRelativePath: parts.dropFirst().joined(separator: "/"),
in: directory,
ignoring: ignoring,
usingCache: false
).map {
results.append($0)
}
}
try _findSourceURL(
forRelativePath: path,
in: directory,
ignoring: ignoring,
usingCache: false
).map {
results.append($0)
}
}
guard results.count <= 1 else {
throw LayoutError.multipleMatches(results, for: path)
}
if usingCache, let url = results.first {
_setSourceURL(url, for: path)
}
return results.first
}
private func _setSourceURL(_ sourceURL: URL, for path: String) {
guard sourceURL.isFileURL else {
preconditionFailure()
}
sourcePaths[path] = sourceURL.path
}
private func _clearSourceURLs() {
sourcePaths.removeAll()
}
#else
private func _findProjectDirectory(at _: String) -> URL? { return nil }
private func _findSourceURL(forRelativePath _: String, in _: URL, ignoring _: [URL], usingCache _: Bool) throws -> URL? { return nil }
private func _setSourceURL(_: URL, for _: String) {}
private func _clearSourceURLs() {}
#endif
| mit | 4dcb1a56a832b271aa61a2f2c6457347 | 33.671614 | 156 | 0.534996 | 5.12843 | false | false | false | false |
335g/TwitterAPIKit | Sources/Models/TokenResult.swift | 1 | 1089 | // Copyright © 2016 Yoshiki Kudo. All rights reserved.
public struct RequestTokenResult {
public let requestToken: String
public let requestTokenSecret: String
public init?(dictionary: [String: AnyObject]){
guard let
requestToken = dictionary["oauth_token"] as? String,
requestTokenSecret = dictionary["oauth_token_secret"] as? String else {
return nil
}
self.requestToken = requestToken
self.requestTokenSecret = requestTokenSecret
}
}
public struct AccessTokenResult {
public let oauthToken: String
public let oauthTokenSecret: String
public let screenName: String
public let userID: Int64
public init?(dictionary: [String: AnyObject]){
guard let
oauthToken = dictionary["oauth_token"] as? String,
oauthTokenSecret = dictionary["oauth_token_secret"] as? String,
screenName = dictionary["screen_name"] as? String,
userID = dictionary["user_id"] as? String else {
return nil
}
self.oauthToken = oauthToken
self.oauthTokenSecret = oauthTokenSecret
self.screenName = screenName
self.userID = Int64(userID)!
}
}
| mit | 0b72658d1575cb83135b3d42eab5a127 | 25.536585 | 74 | 0.729779 | 4.04461 | false | false | false | false |
abhayamrastogi/ChatSDKPodSpecs | rgconnectsdk/NetworkHandlers/UserAuthNetworkHandler.swift | 1 | 6213 | //
// UserAuthNetworkHandler.swift
// rgconnectsdk
//
// Created by Anurag Agnihotri on 20/07/16.
// Copyright © 2016 RoundGlass Partners. All rights reserved.
//
import Foundation
import ObjectMapper
public enum UserPresenceStatus: String {
case Online = "online"
case Away = "away"
case Busy = "busy"
case Offline = "offline"
}
class UserAuthNetworkHandler {
/**
Method to Login to Chat Server using Session Token.
- parameter meteorClient: <#meteorClient description#>
- parameter sessionToken: <#sessionToken description#>
- parameter successCallback: <#successCallback description#>
- parameter errorCallback: <#errorCallback description#>
*/
static func loginWithSessionToken(meteorClient: MeteorClient, sessionToken: String,
successCallback: ((response: [NSObject: AnyObject]) -> Void),
errorCallback: ((error: NSError) -> Void)) {
meteorClient.logonWithSessionToken(sessionToken) { (result, error) in
if error != nil {
errorCallback(error: error)
}
if result != nil {
successCallback(response: result)
}
}
}
/**
Method to Send User Presence Status.
- parameter meteorClient: <#meteorClient description#>
- parameter userPresenceStatus: <#userPresenceStatus description#>
- parameter successCallback: <#successCallback description#>
- parameter errorCallback: <#errorCallback description#>
*/
static func setUserPresenceStatus(meteorClient: MeteorClient,
userPresenceStatus: UserPresenceStatus,
successCallback: ((response: [NSObject: AnyObject]) -> Void),
errorCallback: ((error: NSError) -> Void)) {
meteorClient.callMethodName("UserPresence:setDefaultStatus", parameters: [userPresenceStatus.rawValue]) { (result, error) in
if error != nil {
errorCallback(error: error)
}
if result != nil {
successCallback(response: result)
}
}
}
/**
Method to fetch username suggestions for the user.
- parameter meteorClient: <#meteorClient description#>
- parameter successCallback: <#successCallback description#>
- parameter errorCallback: <#errorCallback description#>
*/
static func getUsernameSuggestions(meteorClient: MeteorClient,
successCallback: ((response: String?) -> Void),
errorCallback: ((error: NSError) -> Void)) {
meteorClient.callMethodName("getUsernameSuggestion", parameters: []) { (result, error) in
if error != nil {
errorCallback(error: error)
}
if result != nil {
let username = result["result"] as? String
successCallback(response: username)
}
}
}
/**
Method to Send Forgot Password Email with Link to the User.
- parameter meteorClient: <#meteorClient description#>
- parameter email: <#email description#>
- parameter successCallback: <#successCallback description#>
- parameter errorCallback: <#errorCallback description#>
*/
static func sendForgotPasswordEmail(meteorClient: MeteorClient, email: String,
successCallback: ((response: [NSObject: AnyObject]) -> Void),
errorCallback: ((error: NSError) -> Void)) {
meteorClient.callMethodName("sendForgotPasswordEmail", parameters: [email]) { (result, error) in
if error != nil {
errorCallback(error: error)
}
if result != nil {
successCallback(response: result)
}
}
}
/**
Method to Set Username for a particular User.
- parameter meteorClient: <#meteorClient description#>
- parameter username: <#username description#>
- parameter successCallback: <#successCallback description#>
- parameter errorCallback: <#errorCallback description#>
*/
static func setUsername(meteorClient: MeteorClient, username: String,
successCallback: ((response: [NSObject: AnyObject]) -> Void),
errorCallback: ((error: NSError) -> Void)) {
meteorClient.callMethodName("setUsername", parameters: []) { (result, error) in
if error != nil {
errorCallback(error: error)
}
if result != nil {
successCallback(response: result)
}
}
}
/**
Method to get Current User from the Users Collection
- parameter meteorClient: <#meteorClient description#>
- parameter successCallback: <#successCallback description#>
- parameter errorCallback: <#errorCallback description#>
*/
static func getCurrentUser(meteorClient: MeteorClient,
successCallback: ((user: User) -> Void),
errorCallback: ((error: NSError) -> Void)) {
let users = meteorClient.collections["users"] as? M13OrderedDictionary
if let users = users {
let user = Mapper<User>().map(users[meteorClient.userId] as! NSDictionary)
successCallback(user: user!)
} else {
let error = NSError(domain: "User Not Found.", code: 0, userInfo: nil)
errorCallback(error: error)
}
}
/**
Method to logout User.
- parameter meteorClient: <#meteorClient description#>
*/
static func logoutUser(meteorClient: MeteorClient) {
meteorClient.logout()
}
} | mit | b0ff7b97be2f81eef07cd39f708f12cf | 34.502857 | 132 | 0.554572 | 5.586331 | false | false | false | false |
KrishMunot/swift | test/attr/attr_autoclosure.swift | 2 | 4010 | // RUN: %target-parse-verify-swift
// Simple case.
@autoclosure var fn : () -> Int = 4 // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{1-14=}} expected-error {{cannot convert value of type 'Int' to specified type '() -> Int'}}
@autoclosure func func1() {} // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{1-14=}}
func func1a(@autoclosure _ v1 : Int) {} // expected-error {{@autoclosure may only be applied to values of function type}}
func func2(@autoclosure _ fp : () -> Int) { func2(4)}
func func3(@autoclosure fp fpx : () -> Int) {func3(fp: 0)}
func func4(@autoclosure fp : () -> Int) {func4(fp: 0)}
func func6(@autoclosure _: () -> Int) {func6(0)}
// declattr and typeattr on the argument.
func func7(@autoclosure _: @noreturn () -> Int) {func7(0)}
// autoclosure + inout don't make sense.
func func8(@autoclosure _ x: inout () -> Bool) -> Bool { // expected-error {{@autoclosure may only be applied to values of function type}}
}
// <rdar://problem/19707366> QoI: @autoclosure declaration change fixit
let migrate4 : @autoclosure() -> () // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@autoclosure }} {{16-28=}}
struct SomeStruct {
@autoclosure let property : () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
init() {
}
}
class BaseClass {
@autoclosure var property : () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
init() {}
}
class DerivedClass {
var property : () -> Int { get {} set {} }
}
protocol P1 {
associatedtype Element
}
protocol P2 : P1 {
associatedtype Element
}
func overloadedEach<O: P1>(_ source: O, _ closure: () -> ()) {
}
func overloadedEach<P: P2>(_ source: P, _ closure: () -> ()) {
}
struct S : P2 {
typealias Element = Int
func each(@autoclosure _ closure: () -> ()) {
overloadedEach(self, closure) // expected-error {{invalid conversion from non-escaping function of type '@autoclosure () -> ()' to potentially escaping function type '() -> ()'}}
}
}
struct AutoclosureEscapeTest {
@autoclosure let delayed: () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
}
// @autoclosure(escaping)
func func10(@autoclosure(escaping _: () -> ()) { } // expected-error{{expected ')' in @autoclosure}}
// expected-note@-1{{to match this opening '('}}
func func11(@autoclosure(escaping) @noescape _: () -> ()) { } // expected-error{{@noescape conflicts with @autoclosure(escaping)}} {{36-46=}}
class Super {
func f1(@autoclosure(escaping) _ x: () -> ()) { }
func f2(@autoclosure(escaping) _ x: () -> ()) { }
func f3(@autoclosure x: () -> ()) { }
}
class Sub : Super {
override func f1(@autoclosure(escaping) _ x: () -> ()) { }
override func f2(@autoclosure _ x: () -> ()) { } // expected-error{{does not override any method}}
override func f3(@autoclosure(escaping) _ x: () -> ()) { } // expected-error{{does not override any method}}
}
func func12_sink(_ x: () -> Int) { }
func func12a(@autoclosure _ x: () -> Int) {
func12_sink(x) // expected-error{{invalid conversion from non-escaping function of type '@autoclosure () -> Int' to potentially escaping function type '() -> Int'}}
}
func func12b(@autoclosure(escaping) _ x: () -> Int) {
func12_sink(x)
}
class TestFunc12 {
var x: Int = 5
func foo() -> Int { return 0 }
func test() {
func12a(x + foo()) // okay
func12b(x + foo())
// expected-error@-1{{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{13-13=self.}}
// expected-error@-2{{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{17-17=self.}}
}
}
enum AutoclosureFailableOf<T> {
case Success(@autoclosure () -> T) // expected-error {{attribute can only be applied to declarations, not types}}
case Failure()
}
| apache-2.0 | a534a1e0e81cd5a6234f928ba2fac458 | 33.273504 | 210 | 0.641646 | 3.625678 | false | false | false | false |
jiangboLee/huangpian | liubai/Photos/controller/filters/FilterCollectionView.swift | 1 | 2426 | //
// FilterCollectionView.swift
// liubai
//
// Created by 李江波 on 2017/3/24.
// Copyright © 2017年 lijiangbo. All rights reserved.
//
import UIKit
class FilterCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource {
let FilterCollectionViewCellID = "FilterCollectionViewCellID"
let filterImgArr = ["美颜", "原图", "怀旧", "绿巨人", "卡通", "素描", "水晶球", "浮雕", "上下模糊"]
var clickItem: ((_ item: Int)->())?
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 80), collectionViewLayout: FilterCollectionViewFlowLayout())
backgroundColor = UIColor.clear
delegate = self
dataSource = self
bounces = false
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
register(UINib(nibName: "FilterCollectionCell", bundle: nil), forCellWithReuseIdentifier: FilterCollectionViewCellID)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filterImgArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FilterCollectionViewCellID, for: indexPath) as! FilterCollectionCell
cell.filterName.text = filterImgArr[indexPath.row]
cell.filterImg.image = UIImage(named: String(indexPath.row + 1))
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
clickItem?(indexPath.item)
}
}
class FilterCollectionViewFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
let margin: CGFloat = 8.0
let width = (SCREENW - margin * 4.0) / 5.0
itemSize = CGSize(width: width, height: width)
minimumLineSpacing = margin
minimumInteritemSpacing = 0
scrollDirection = .horizontal
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 7a5702a3452d9cf36c4815a92de89091 | 33.897059 | 143 | 0.678045 | 4.974843 | false | false | false | false |
LeoNatan/LNPopupController | LNPopupControllerExample/LNPopupControllerExample/MapViewController.swift | 1 | 3858 | //
// MapViewController.swift
// LNPopupControllerExample
//
// Created by Leo Natan on 30/12/2016.
// Copyright © 2016 Leo Natan. All rights reserved.
//
#if LNPOPUP
import LNPopupController
#endif
import UIKit
import MapKit
class MapViewController: UIViewController, UISearchBarDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var topVisualEffectView: UIVisualEffectView!
@IBOutlet weak var backButtonBackground: UIVisualEffectView!
private var popupContentVC: LocationsController!
override func viewDidLoad() {
super.viewDidLoad()
mapView.showsTraffic = false
mapView.pointOfInterestFilter = .includingAll
backButtonBackground.layer.cornerRadius = 10.0
backButtonBackground.layer.borderWidth = 1.0
backButtonBackground.layer.borderColor = self.view.tintColor.cgColor
topVisualEffectView.effect = UIBlurEffect(blurRadius: 10.0)
backButtonBackground.effect = UIBlurEffect(style: .systemChromeMaterial)
backButtonBackground.layer.cornerCurve = .continuous
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
backButtonBackground.layer.borderColor = self.view.tintColor.cgColor
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.presentPopupBarIfNeeded(animated: false)
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
#if LNPOPUP
openPopup(animated: true, completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.popupContentVC.searchBar.becomeFirstResponder()
}
#endif
return false;
}
@IBAction private func presentButtonTapped(_ sender: Any) {
presentPopupBarIfNeeded(animated: true)
}
private func presentPopupBarIfNeeded(animated: Bool) {
#if LNPOPUP
guard popupBar.customBarViewController == nil else {
return
}
popupBar.standardAppearance.shadowColor = .clear
if let customMapBar = storyboard!.instantiateViewController(withIdentifier: "CustomMapBarViewController") as? CustomMapBarViewController {
popupBar.customBarViewController = customMapBar
customMapBar.view.backgroundColor = .clear
customMapBar.searchBar.delegate = self
if let searchTextField = customMapBar.searchBar.value(forKey: "searchField") as? UITextField, let clearButton = searchTextField.value(forKey: "_clearButton") as? UIButton {
clearButton.addTarget(self, action: #selector(self.clearButtonTapped), for: .primaryActionTriggered)
}
popupBar.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
popupBar.layer.cornerRadius = 15
popupBar.layer.cornerCurve = .continuous
} else {
//Manual layout bar scene
shouldExtendPopupBarUnderSafeArea = false
popupBar.customBarViewController = ManualLayoutCustomBarViewController()
popupBar.standardAppearance.configureWithTransparentBackground()
}
popupContentView.popupCloseButtonStyle = .none
popupContentView.backgroundEffect = UIBlurEffect(style: .systemChromeMaterial)
// popupContentView.isTranslucent = false
popupInteractionStyle = .customizedSnap(percent: 0.15)
popupContentVC = (storyboard!.instantiateViewController(withIdentifier: "PopupContentController") as! LocationsController)
popupContentVC.tableView.backgroundColor = .clear
presentPopupBar(withContentViewController: self.popupContentVC, animated: animated, completion: nil)
#endif
}
@objc private func clearButtonTapped(_ sender: Any) {
#if LNPOPUP
popupContentVC.popupItem.title = nil
popupContentVC.searchBar.text = nil
#endif
}
@IBAction private func dismissButtonTapped(_ sender: Any) {
#if LNPOPUP
dismissPopupBar(animated: true) {
self.popupBar.customBarViewController = nil
}
#endif
}
override var shouldFadePopupBarOnDismiss: Bool {
return true
}
}
| mit | 4c92e426fd9b767442505a97eface4fc | 30.876033 | 175 | 0.782733 | 4.257174 | false | false | false | false |
dcunited001/SpectraNu | SpectraTests/SpectraXMLSpec.swift | 1 | 6678 | //
// SpectraXMLSpec.swift
//
//
// Created by David Conner on 2/23/16.
//
//
@testable import Spectra
import Quick
import Nimble
import ModelIO
import Swinject
import Metal
import simd
class SpectraXMLSpec: QuickSpec {
override func spec() {
// let parser = Container()
//
// let spectraEnumData = SpectraXSD.readXSD("SpectraEnums")
// let spectraEnumXSD = SpectraXSD(data: spectraEnumData)
// spectraEnumXSD.parseEnumTypes(parser)
//
// let testBundle = NSBundle(forClass: SpectraXMLSpec.self)
// let xmlData: NSData = SpectraXML.readXML(testBundle, filename: "SpectraXMLSpec")
// let assetContainer = Container(parent: parser)
// ModelIOTextureGenerators.loadTextureGenerators(assetContainer)
//
// SpectraXML.initParser(parser)
// let spectraXML = SpectraXML(parser: parser, data: xmlData)
// spectraXML.parse(assetContainer, options: [:])
//
// // TODO: move this to a new file?
// describe("SpectraXML: main parser") {
// describe("parser can register new D/I handlers for XML tags") {
// // this kinda requires auto-injection, which isn't available for swinject
// }
//
// describe("parser can also register custom types to return") {
// it("allows resolution of SpectraXMLNodeType with custom types") {
//
// }
// }
// }
//
// // TODO: convert from VertexDescriptor with array-of-struct to struct-of-array indexing
// // TODO: convert MDLVertexDescriptor <=> MTLVertexDescriptor
//
// describe("world-view") {
// it("can parse world view nodes") {
// // should it create a separate 'world-object' with it's own transform hierarchy?
// }
// }
//
// describe("object") {
// let scene1: MDLObject = self.containerGet(assetContainer, id: "scene1")!
//
// it("can create basic objects") {
// let objDefault: MDLObject = self.containerGet(assetContainer, id: "default")!
// expect(objDefault.transform).to(beNil())
// expect(objDefault.name) == "default"
// }
//
// it("can create nested objects") {
// let xform: MDLTransform = self.containerGet(assetContainer, id: "xform_translate")!
// let cam: MDLCamera = self.containerGet(assetContainer, id: "default")!
// let stereoCam: MDLStereoscopicCamera = self.containerGet(assetContainer, id: "default")!
//
// expect(scene1.children)
// }
//
// it("can create root objects that can be used to contain other objects") {
// // i think this is the best place for this?
// // - or object container?
// }
// }
//
// describe("asset") {
//// let pencils = assetContainer.resolve(MDLAsset.self, name: "pencil_model")!
//
// it("can parse asset nodes") {
//
// }
//
// it("can generate asset nodes") {
// // TODO: how to generate environment-independent path?
// }
//
// it ("can generate asset nodes with a vertex descriptor and/or buffer allocator") {
//
// }
// }
// describe("light") {
// // TODO: finish filling out attributes
// // - MDLLightProbe
// // - MDLPhysicallyPlausibleLight
// // - MDLPhotometricLight
// }
//
// describe("material") {
// // initWithName:scatteringFunction:
// // - name: String
// // - scatteringFunction: MDLScatteringFunction (required)
// // - baseMaterial: MDLMaterial? (parent material which can material properties)
// }
//
// describe("material-property") {
//
// // - initWithName:semantic:URL:
// // - initWithName:semantic:textureSampler:
// // - initWithName:semantic:color:
// // - initWithName:semantic:float:
// // - initWithName:semantic:float2:
// // - initWithName:semantic:float3:
// // - initWithName:semantic:float4:
// // - initWithName:semantic:matrix4x4:
//
// // name: String
// // semantic: MDLMaterialSemantic
// // type: MDLMaterialPropertyType
// // stringValue: String?
// // URLValue: NSUrl?
// // textureSamplerValue: MDLTextureSampler
// // color: CGColor?
// // floatValue: Float
// // float2Value: vector_float2
// // float3Value: vector_float3
// // float4Value: vector_float4
// // matrix4x4: matrix_float4x4
//
// // copy with setProperties:MDLMaterialProperty
//
// // enum: MDLMaterialSemantic
// // enum: MDLMaterialPropertyType
// }
//
// describe("scattering-function") {
// // defines response to lighting for a MDLMaterial object
// // - i'll need to be knee deep in shaders before messing with this
// // - and depthStencils with blitting, i think
//
// // name: String
// // baseColor: MDLMaterialProperty
// // emission: MDLMaterialProperty
// // specular: MDLMaterialProperty
// // materialIndexOfRefraction: MDLMaterialProperty
// // interfaceIndexOfRefraction: MDLMaterialProperty
// // normal: MDLMaterialProperty
// // ambientOcclusion: MDLMaterialProperty
// // ambientOcclusionScale: MDLMaterialProperty
//
// // also includes MDLPhysicallyPlausibleScatteringFunction:
// //
// // subsurface: MDLMaterialProperty
// // metallic: MDLMaterialProperty
// // specularAmount: MDLMaterialProperty
// // specularTint: MDLMaterialProperty
// // roughness: MDLMaterialProperty
// // anisotropic: MDLMaterialProperty
// // anisotropicRotation: MDLMaterialProperty
// // sheen: MDLMaterialProperty
// // sheenTint: MDLMaterialProperty
// // clearcoat: MDLMaterialProperty
// }
//
// describe("voxel-array") {
// // transformations to voxels from meshes that are already loaded
// }
}
}
| mit | 6f457af9d7eb8313201a2bfc335fd39b | 37.16 | 106 | 0.538934 | 4.32513 | false | false | false | false |
inacioferrarini/OMDBSpy | OMDBSpy/Foundation/ViewController/BaseViewController.swift | 1 | 1292 | import UIKit
class BaseViewController: UIViewController, AppContextAwareProtocol {
// MARK: - Properties
var appContext: AppContext!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.translateUI()
}
// MARK: - i18n
func viewControllerTitle() -> String? { return nil }
func translateUI() {
if let title = self.viewControllerTitle() {
self.navigationItem.title = title
}
for view in self.view.subviews as [UIView] {
if let label = view as? UILabel {
if let identifier = label.accessibilityIdentifier {
let text = localizedBundleString(identifier)
if (text == identifier) {
self.appContext.logger.logErrorMessage("Missing string for \(identifier)")
} else {
label.text = text
}
}
}
}
}
func localizedBundleString(key: String) -> String {
let bundle = NSBundle(forClass: self.dynamicType)
return NSLocalizedString(key, tableName: nil, bundle: bundle, value: "", comment: "")
}
}
| mit | caf8f7791343c735e24764d7fdede300 | 25.916667 | 98 | 0.520124 | 5.497872 | false | false | false | false |
ihomway/RayWenderlichCourses | Intermediate Swift 3/Intermediate Swift 3.playground/Pages/Protocols.xcplaygroundpage/Contents.swift | 1 | 913 | //: [Previous](@previous)
import Foundation
var str = "Hello, playground"
protocol Vehicle {
func accelerate()
func stop()
}
protocol Music {
func play()
}
class Transport {
}
class Unicycle: Vehicle {
var peddling = false
func accelerate() {
print("squeaky squeaky")
peddling = true
}
func stop() {
peddling = false
}
}
class Car: Transport, Vehicle, Music {
var velocity = 0
func accelerate() {
print("vrrrroom")
velocity += 4
}
func stop() {
velocity = 0
}
func play() {
//
}
}
class Cat {
}
class Boat {
var knot = 0
}
extension Boat: Vehicle {
func accelerate() {
print("swish swish")
knot += 10
}
func stop() {
knot = 0
}
}
var vehicles: [Vehicle] = []
vehicles.append(Car())
vehicles.append(Unicycle())
//vehicles.append(Cat())
vehicles.append(Boat())
for vehicle in vehicles {
vehicle.accelerate()
// vehicle.stop()
}
//: [Next](@next)
| mit | 0875a01aaa413a9ea705ac27764ae576 | 10.556962 | 38 | 0.624315 | 2.717262 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/WordPressStatsWidgets/Model/HomeWidgetData.swift | 2 | 2032 | import WidgetKit
protocol HomeWidgetData: Codable {
var siteID: Int { get }
var siteName: String { get }
var url: String { get }
var timeZone: TimeZone { get }
var date: Date { get }
static var filename: String { get }
}
// MARK: - Local cache
extension HomeWidgetData {
static func read(from cache: HomeWidgetCache<Self>? = nil) -> [Int: Self]? {
let cache = cache ?? HomeWidgetCache<Self>(fileName: Self.filename,
appGroup: WPAppGroupName)
do {
return try cache.read()
} catch {
DDLogError("HomeWidgetToday: Failed loading data: \(error.localizedDescription)")
return nil
}
}
static func write(items: [Int: Self], to cache: HomeWidgetCache<Self>? = nil) {
let cache = cache ?? HomeWidgetCache<Self>(fileName: Self.filename,
appGroup: WPAppGroupName)
do {
try cache.write(items: items)
} catch {
DDLogError("HomeWidgetToday: Failed writing data: \(error.localizedDescription)")
}
}
static func delete(cache: HomeWidgetCache<Self>? = nil) {
let cache = cache ?? HomeWidgetCache<Self>(fileName: Self.filename,
appGroup: WPAppGroupName)
do {
try cache.delete()
} catch {
DDLogError("HomeWidgetToday: Failed deleting data: \(error.localizedDescription)")
}
}
static func setItem(item: Self, to cache: HomeWidgetCache<Self>? = nil) {
let cache = cache ?? HomeWidgetCache<Self>(fileName: Self.filename,
appGroup: WPAppGroupName)
do {
try cache.setItem(item: item)
} catch {
DDLogError("HomeWidgetToday: Failed writing data item: \(error.localizedDescription)")
}
}
}
| gpl-2.0 | fe0575495f16b32df7809ba2d05173b0 | 31.253968 | 98 | 0.53248 | 4.920097 | false | false | false | false |
ptangen/equityStatus | EquityStatus/Utilities.swift | 1 | 2815 | //
// Utilities.swift
// EquityStatus
//
// Created by Paul Tangen on 12/19/16.
// Copyright © 2016 Paul Tangen. All rights reserved.
//
import Foundation
import UIKit
class Utilities {
// The api return status values such as pass, fail, noData, 100, 101 and 200. Convert these values to unicode value of the font icon.
class func getStatusIcon(status: Bool?, uiLabel: UILabel) {
if let statusUnwrapped = status {
if statusUnwrapped {
uiLabel.text = "p" //Constants.iconLibrary.faCheckCircle.rawValue // passed
uiLabel.textColor = UIColor(named: .statusGreen)
} else {
uiLabel.text = "f" //Constants.iconLibrary.faTimesCircle.rawValue // failed
uiLabel.textColor = UIColor(named: .statusRed)
}
} else {
uiLabel.text = "?" //Constants.iconLibrary.faCircleO.rawValue // missing
uiLabel.textColor = UIColor(named: .disabledText)
}
}
class func getMeasureLongName(measure: String) -> String {
switch measure {
case "roe_avg":
return "Avg Return on Equity"
case "eps_i":
return "Earnings Per Share Growth Rate"
case "eps_sd":
return "Earnings Per Share Volatility"
case "bv_i":
return "Book Value Growth Rate"
case "dr_avg":
return "Avg Debt Ratio"
case "so_reduced":
return "Shares Outstanding Reduced"
case "previous_roi":
return "Previous Return on Investment"
case "expected_roi":
return "Expected Return on Investment"
case "q1":
return "Is there a strong upward trend in the EPS?"
case "q2":
return "Do you understand the product/service?"
case "q3":
return "Has the product/service been consistent for 10 years?"
case "q4":
return "Does the company invest in it's area of expertise?"
case "q5":
return "Are few expenditures required to maintain operations?"
case "q6":
return "Is the company free to adjust prices with inflation?"
default:
return ""
}
}
class func showAlertMessage(_ message: String, viewControllerInst: UIViewController) {
let alertController = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default,handler: nil))
viewControllerInst.present(alertController, animated: true, completion: nil)
}
}
| apache-2.0 | b10a016f705a38bb1e1abf783371d3c8 | 38.633803 | 137 | 0.580668 | 4.674419 | false | false | false | false |
erhoffex/SwiftAnyPic | SwiftAnyPic/PAPFindFriendsViewController.swift | 5 | 24970 | import UIKit
import MessageUI
import ParseUI
import AddressBookUI
import MBProgressHUD
import Synchronized
enum PAPFindFriendsFollowStatus: Int {
case FollowingNone = 0, // User isn't following anybody in Friends list
FollowingAll, // User is following all Friends
FollowingSome // User is following some of their Friends
}
class PAPFindFriendsViewController: PFQueryTableViewController, PAPFindFriendsCellDelegate, ABPeoplePickerNavigationControllerDelegate, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate, UIActionSheetDelegate {
private var headerView: UIView?
private var followStatus: PAPFindFriendsFollowStatus
private var selectedEmailAddress: String
private var outstandingFollowQueries: [NSObject: AnyObject]
private var outstandingCountQueries: [NSIndexPath: AnyObject]
// MARK:- Initialization
init(style: UITableViewStyle) {
self.selectedEmailAddress = ""
// Used to determine Follow/Unfollow All button status
self.followStatus = PAPFindFriendsFollowStatus.FollowingSome
self.outstandingFollowQueries = [NSObject: AnyObject]()
self.outstandingCountQueries = [NSIndexPath: AnyObject]()
super.init(style: style, className: nil)
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = true
// The number of objects to show per page
self.objectsPerPage = 15
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.tableView.backgroundColor = UIColor.blackColor()
self.navigationItem.titleView = UIImageView(image: UIImage(named: "TitleFindFriends.png"))
if self.navigationController!.viewControllers[0] == self {
let dismissLeftBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismissPresentingViewController"))
self.navigationItem.leftBarButtonItem = dismissLeftBarButtonItem
} else {
self.navigationItem.leftBarButtonItem = nil
}
if MFMailComposeViewController.canSendMail() || MFMessageComposeViewController.canSendText() {
self.headerView = UIView(frame: CGRectMake(0, 0, 320, 67))
self.headerView!.backgroundColor = UIColor.blackColor()
let clearButton = UIButton(type: UIButtonType.Custom)
clearButton.backgroundColor = UIColor.clearColor()
clearButton.addTarget(self, action: Selector("inviteFriendsButtonAction:"), forControlEvents: UIControlEvents.TouchUpInside)
clearButton.frame = self.headerView!.frame
self.headerView!.addSubview(clearButton)
let inviteString = NSLocalizedString("Invite friends", comment: "Invite friends")
let boundingRect: CGRect = inviteString.boundingRectWithSize(CGSizeMake(310.0, CGFloat.max),
options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin],
attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(18.0)],
context: nil)
let inviteStringSize: CGSize = boundingRect.size
let inviteLabel = UILabel(frame: CGRectMake(10, (self.headerView!.frame.size.height-inviteStringSize.height)/2, inviteStringSize.width, inviteStringSize.height))
inviteLabel.text = inviteString
inviteLabel.font = UIFont.boldSystemFontOfSize(18)
inviteLabel.textColor = UIColor.whiteColor()
inviteLabel.backgroundColor = UIColor.clearColor()
self.headerView!.addSubview(inviteLabel)
self.tableView!.tableHeaderView = self.headerView
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.separatorColor = UIColor(red: 30.0/255.0, green: 30.0/255.0, blue: 30.0/255.0, alpha: 1.0)
}
func dismissPresentingViewController() {
self.navigationController!.dismissViewControllerAnimated(true, completion: nil)
}
// MARK:- UITableViewDelegate
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row < self.objects!.count {
return PAPFindFriendsCell.heightForCell()
} else {
return 44.0
}
}
// MARK:- PFQueryTableViewController
override func queryForTable() -> PFQuery {
// Use cached facebook friend ids
let facebookFriends: [PFUser]? = PAPCache.sharedCache.facebookFriends()
// Query for all friends you have on facebook and who are using the app
let friendsQuery: PFQuery = PFUser.query()!
friendsQuery.whereKey(kPAPUserFacebookIDKey, containedIn: facebookFriends!)
// Query for all Parse employees
var parseEmployees: [String] = kPAPParseEmployeeAccounts
let currentUserFacebookId = PFUser.currentUser()!.objectForKey(kPAPUserFacebookIDKey) as! String
parseEmployees = parseEmployees.filter { (facebookId) in facebookId != currentUserFacebookId }
let parseEmployeeQuery: PFQuery = PFUser.query()!
parseEmployeeQuery.whereKey(kPAPUserFacebookIDKey, containedIn: parseEmployees)
let query: PFQuery = PFQuery.orQueryWithSubqueries([friendsQuery, parseEmployeeQuery])
query.cachePolicy = PFCachePolicy.NetworkOnly
if self.objects!.count == 0 {
query.cachePolicy = PFCachePolicy.CacheThenNetwork
}
query.orderByAscending(kPAPUserDisplayNameKey)
return query
}
override func objectsDidLoad(error: NSError?) {
super.objectsDidLoad(error)
let isFollowingQuery = PFQuery(className: kPAPActivityClassKey)
isFollowingQuery.whereKey(kPAPActivityFromUserKey, equalTo: PFUser.currentUser()!)
isFollowingQuery.whereKey(kPAPActivityTypeKey, equalTo: kPAPActivityTypeFollow)
isFollowingQuery.whereKey(kPAPActivityToUserKey, containedIn: self.objects!)
isFollowingQuery.cachePolicy = PFCachePolicy.NetworkOnly
isFollowingQuery.countObjectsInBackgroundWithBlock { (number, error) in
if error == nil {
if Int(number) == self.objects!.count {
self.followStatus = PAPFindFriendsFollowStatus.FollowingAll
self.configureUnfollowAllButton()
for user in self.objects as! [PFUser] {
PAPCache.sharedCache.setFollowStatus(true, user: user)
}
} else if number == 0 {
self.followStatus = PAPFindFriendsFollowStatus.FollowingNone
self.configureFollowAllButton()
for user in self.objects as! [PFUser] {
PAPCache.sharedCache.setFollowStatus(false, user: user)
}
} else {
self.followStatus = PAPFindFriendsFollowStatus.FollowingSome
self.configureFollowAllButton()
}
}
if self.objects!.count == 0 {
self.navigationItem.rightBarButtonItem = nil
}
}
if self.objects!.count == 0 {
self.navigationItem.rightBarButtonItem = nil
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
let FriendCellIdentifier = "FriendCell"
var cell: PAPFindFriendsCell? = tableView.dequeueReusableCellWithIdentifier(FriendCellIdentifier) as? PAPFindFriendsCell
if cell == nil {
cell = PAPFindFriendsCell(style: UITableViewCellStyle.Default, reuseIdentifier: FriendCellIdentifier)
cell!.delegate = self
}
cell!.user = object as? PFUser
cell!.photoLabel!.text = "0 photos"
let attributes: [NSObject: AnyObject]? = PAPCache.sharedCache.attributesForUser(object as! PFUser)
if attributes != nil {
// set them now
let number = PAPCache.sharedCache.photoCountForUser(object as! PFUser)
let appendS = number == 1 ? "": "s"
cell!.photoLabel.text = "\(number) photo\(appendS)"
} else {
synchronized(self) {
let outstandingCountQueryStatus: Int? = self.outstandingCountQueries[indexPath] as? Int
if outstandingCountQueryStatus == nil {
self.outstandingCountQueries[indexPath] = true
let photoNumQuery = PFQuery(className: kPAPPhotoClassKey)
photoNumQuery.whereKey(kPAPPhotoUserKey, equalTo: object!)
photoNumQuery.cachePolicy = PFCachePolicy.CacheThenNetwork
photoNumQuery.countObjectsInBackgroundWithBlock { (number, error) in
synchronized(self) {
PAPCache.sharedCache.setPhotoCount(Int(number), user: object as! PFUser)
self.outstandingCountQueries.removeValueForKey(indexPath)
}
let actualCell: PAPFindFriendsCell? = tableView.cellForRowAtIndexPath(indexPath) as? PAPFindFriendsCell
let appendS = number == 1 ? "" : "s"
actualCell?.photoLabel?.text = "\(number) photo\(appendS)"
}
}
}
}
cell!.followButton.selected = false
cell!.tag = indexPath.row
if self.followStatus == PAPFindFriendsFollowStatus.FollowingSome {
if attributes != nil {
cell!.followButton.selected = PAPCache.sharedCache.followStatusForUser(object as! PFUser)
} else {
synchronized(self) {
let outstandingQuery: Int? = self.outstandingFollowQueries[indexPath] as? Int
if outstandingQuery == nil {
self.outstandingFollowQueries[indexPath] = true
let isFollowingQuery = PFQuery(className: kPAPActivityClassKey)
isFollowingQuery.whereKey(kPAPActivityFromUserKey, equalTo: PFUser.currentUser()!)
isFollowingQuery.whereKey(kPAPActivityTypeKey, equalTo: kPAPActivityTypeFollow)
isFollowingQuery.whereKey(kPAPActivityToUserKey, equalTo: object!)
isFollowingQuery.cachePolicy = PFCachePolicy.CacheThenNetwork
isFollowingQuery.countObjectsInBackgroundWithBlock { (number, error) in
synchronized(self) {
self.outstandingFollowQueries.removeValueForKey(indexPath)
PAPCache.sharedCache.setFollowStatus((error == nil && number > 0), user: object as! PFUser)
}
if cell!.tag == indexPath.row {
cell!.followButton.selected = (error == nil && number > 0)
}
}
}
}
}
} else {
cell!.followButton.selected = (self.followStatus == PAPFindFriendsFollowStatus.FollowingAll)
}
return cell!
}
override func tableView(tableView: UITableView, cellForNextPageAtIndexPath indexPath: NSIndexPath) -> PFTableViewCell? {
let NextPageCellIdentifier = "NextPageCell"
var cell: PAPLoadMoreCell? = tableView.dequeueReusableCellWithIdentifier(NextPageCellIdentifier) as? PAPLoadMoreCell
if cell == nil {
cell = PAPLoadMoreCell(style: UITableViewCellStyle.Default, reuseIdentifier: NextPageCellIdentifier)
cell!.mainView!.backgroundColor = UIColor.blackColor()
cell!.hideSeparatorBottom = true
cell!.hideSeparatorTop = true
}
cell!.selectionStyle = UITableViewCellSelectionStyle.None
return cell!
}
// MARK:- PAPFindFriendsCellDelegate
func cell(cellView: PAPFindFriendsCell, didTapUserButton aUser: PFUser) {
// Push account view controller
let accountViewController = PAPAccountViewController(user: aUser)
print("Presenting account view controller with user: \(aUser)")
self.navigationController!.pushViewController(accountViewController, animated: true)
}
func cell(cellView: PAPFindFriendsCell, didTapFollowButton aUser: PFUser) {
self.shouldToggleFollowFriendForCell(cellView)
}
// MARK:- ABPeoplePickerDelegate
/* Called when the user cancels the address book view controller. We simply dismiss it. */
// FIXME!!!!!!!!!
func peoplePickerNavigationControllerDidCancel(peoplePicker: ABPeoplePickerNavigationController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
/* Called when a member of the address book is selected, we return YES to display the member's details. */
func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, shouldContinueAfterSelectingPerson person: ABRecord) -> Bool {
return true
}
/* Called when the user selects a property of a person in their address book (ex. phone, email, location,...)
This method will allow them to send a text or email inviting them to Anypic. */
func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, shouldContinueAfterSelectingPerson person: ABRecord, property: ABPropertyID, identifier: ABMultiValueIdentifier) -> Bool {
// if property == kABPersonEmailProperty {
// let emailProperty: ABMultiValueRef = ABRecordCopyValue(person,property)
// let email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emailProperty,identifier);
// self.selectedEmailAddress = email;
//
// if ([MFMailComposeViewController canSendMail] && [MFMessageComposeViewController canSendText]) {
// // ask user
// UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:[NSString stringWithFormat:@"Invite %@",@""] delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Email", @"iMessage", nil];
// [actionSheet showFromTabBar:self.tabBarController.tabBar];
// } else if ([MFMailComposeViewController canSendMail]) {
// // go directly to mail
// [self presentMailComposeViewController:email];
// } else if ([MFMessageComposeViewController canSendText]) {
// // go directly to iMessage
// [self presentMessageComposeViewController:email];
// }
//
// } else if (property == kABPersonPhoneProperty) {
// ABMultiValueRef phoneProperty = ABRecordCopyValue(person,property);
// NSString *phone = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phoneProperty,identifier);
//
// if ([MFMessageComposeViewController canSendText]) {
// [self presentMessageComposeViewController:phone];
// }
// }
return false
}
// MARK:- MFMailComposeDelegate
/* Simply dismiss the MFMailComposeViewController when the user sends an email or cancels */
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK:- MFMessageComposeDelegate
/* Simply dismiss the MFMessageComposeViewController when the user sends a text or cancels */
func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK:- UIActionSheetDelegate
// FIXME!!!!!!!!
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == actionSheet.cancelButtonIndex {
return
}
if buttonIndex == 0 {
self.presentMailComposeViewController(self.selectedEmailAddress)
} else if buttonIndex == 1 {
self.presentMessageComposeViewController(self.selectedEmailAddress)
}
}
// MARK:- ()
func backButtonAction(sender: AnyObject) {
self.navigationController!.popViewControllerAnimated(true)
}
func inviteFriendsButtonAction(sender: AnyObject) {
let addressBook = ABPeoplePickerNavigationController()
addressBook.peoplePickerDelegate = self
if MFMailComposeViewController.canSendMail() && MFMessageComposeViewController.canSendText() {
addressBook.displayedProperties = [Int(kABPersonEmailProperty), Int(kABPersonPhoneProperty)]
} else if MFMailComposeViewController.canSendMail() {
addressBook.displayedProperties = [Int(kABPersonEmailProperty)]
} else if MFMessageComposeViewController.canSendText() {
addressBook.displayedProperties = [Int(kABPersonPhoneProperty)]
}
self.presentViewController(addressBook, animated: true, completion: nil)
}
func followAllFriendsButtonAction(sender: AnyObject) {
MBProgressHUD.showHUDAddedTo(UIApplication.sharedApplication().keyWindow, animated: true)
self.followStatus = PAPFindFriendsFollowStatus.FollowingAll
self.configureUnfollowAllButton()
let popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.01 * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue(), {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Unfollow All", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("unfollowAllFriendsButtonAction:"))
var indexPaths = Array<NSIndexPath>(count: self.objects!.count, repeatedValue: NSIndexPath())
for var r = 0; r < self.objects!.count; r++ {
let user: PFObject = self.objects![r] as! PFObject
let indexPath: NSIndexPath = NSIndexPath(forRow: r, inSection: 0)
let cell: PAPFindFriendsCell? = self.tableView(self.tableView, cellForRowAtIndexPath: indexPath, object: user) as? PAPFindFriendsCell
cell!.followButton.selected = true
indexPaths.append(indexPath)
}
self.tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None)
MBProgressHUD.hideAllHUDsForView(UIApplication.sharedApplication().keyWindow, animated: true)
let timer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: Selector("followUsersTimerFired:"), userInfo: nil, repeats: false)
PAPUtility.followUsersEventually(self.objects as! [PFUser], block: { (succeeded, error) in
// note -- this block is called once for every user that is followed successfully. We use a timer to only execute the completion block once no more saveEventually blocks have been called in 2 seconds
timer.fireDate = NSDate(timeIntervalSinceNow: 2.0)
})
})
}
func unfollowAllFriendsButtonAction(sender: AnyObject) {
MBProgressHUD.showHUDAddedTo(UIApplication.sharedApplication().keyWindow, animated: true)
self.followStatus = PAPFindFriendsFollowStatus.FollowingNone
self.configureFollowAllButton()
let popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.01 * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue(), {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Follow All", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("followAllFriendsButtonAction:"))
var indexPaths: [NSIndexPath] = Array<NSIndexPath>(count: self.objects!.count, repeatedValue: NSIndexPath())
for var r = 0; r < self.objects!.count; r++ {
let user: PFObject = self.objects![r] as! PFObject
let indexPath: NSIndexPath = NSIndexPath(forRow: r, inSection: 0)
let cell: PAPFindFriendsCell = self.tableView(self.tableView, cellForRowAtIndexPath: indexPath, object: user) as! PAPFindFriendsCell
cell.followButton.selected = false
indexPaths.append(indexPath)
}
self.tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None)
MBProgressHUD.hideAllHUDsForView(UIApplication.sharedApplication().keyWindow, animated: true)
PAPUtility.unfollowUsersEventually(self.objects as! [PFUser])
NSNotificationCenter.defaultCenter().postNotificationName(PAPUtilityUserFollowingChangedNotification, object: nil)
})
}
func shouldToggleFollowFriendForCell(cell: PAPFindFriendsCell) {
let cellUser: PFUser = cell.user!
if cell.followButton.selected {
// Unfollow
cell.followButton.selected = false
PAPUtility.unfollowUserEventually(cellUser)
NSNotificationCenter.defaultCenter().postNotificationName(PAPUtilityUserFollowingChangedNotification, object: nil)
} else {
// Follow
cell.followButton.selected = true
PAPUtility.followUserEventually(cellUser, block: { (succeeded, error) in
if error == nil {
NSNotificationCenter.defaultCenter().postNotificationName(PAPUtilityUserFollowingChangedNotification, object: nil)
} else {
cell.followButton.selected = false
}
})
}
}
func configureUnfollowAllButton() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Unfollow All", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("unfollowAllFriendsButtonAction:"))
}
func configureFollowAllButton() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Follow All", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("followAllFriendsButtonAction:"))
}
func presentMailComposeViewController(recipient: String) {
// Create the compose email view controller
let composeEmailViewController = MFMailComposeViewController()
// Set the recipient to the selected email and a default text
composeEmailViewController.mailComposeDelegate = self
composeEmailViewController.setSubject("Join me on Anypic")
composeEmailViewController.setToRecipients([recipient])
composeEmailViewController.setMessageBody("<h2>Share your pictures, share your story.</h2><p><a href=\"http://anypic.org\">Anypic</a> is the easiest way to share photos with your friends. Get the app and share your fun photos with the world.</p><p><a href=\"http://anypic.org\">Anypic</a> is fully powered by <a href=\"http://parse.com\">Parse</a>.</p>", isHTML: true)
// Dismiss the current modal view controller and display the compose email one.
// Note that we do not animate them. Doing so would require us to present the compose
// mail one only *after* the address book is dismissed.
self.dismissViewControllerAnimated(false, completion: nil)
self.presentViewController(composeEmailViewController, animated: false, completion: nil)
}
func presentMessageComposeViewController(recipient: String) {
// Create the compose text message view controller
let composeTextViewController = MFMessageComposeViewController()
// Send the destination phone number and a default text
composeTextViewController.messageComposeDelegate = self
composeTextViewController.recipients = [recipient]
composeTextViewController.body = "Check out Anypic! http://anypic.org"
// Dismiss the current modal view controller and display the compose text one.
// See previous use for reason why these are not animated.
self.dismissViewControllerAnimated(false, completion: nil)
self.presentViewController(composeTextViewController, animated: false, completion: nil)
}
func followUsersTimerFired(timer: NSTimer) {
self.tableView.reloadData()
NSNotificationCenter.defaultCenter().postNotificationName(PAPUtilityUserFollowingChangedNotification, object: nil)
}
}
| cc0-1.0 | f400ae015614b95535dbf88dfb17cbe0 | 48.840319 | 376 | 0.670044 | 5.431803 | false | false | false | false |
stephentyrone/swift | test/AutoDiff/Sema/DerivedConformances/class_differentiable.swift | 1 | 17865 | // RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/class_differentiable_other_module.swift
import _Differentiation
// Verify that a type `T` conforms to `AdditiveArithmetic`.
func assertConformsToAdditiveArithmetic<T>(_: T.Type)
where T: AdditiveArithmetic {}
// Dummy protocol with default implementations for `AdditiveArithmetic` requirements.
// Used to test `Self : AdditiveArithmetic` requirements.
protocol DummyAdditiveArithmetic: AdditiveArithmetic {}
extension DummyAdditiveArithmetic {
static func == (lhs: Self, rhs: Self) -> Bool {
fatalError()
}
static var zero: Self {
fatalError()
}
static func + (lhs: Self, rhs: Self) -> Self {
fatalError()
}
static func - (lhs: Self, rhs: Self) -> Self {
fatalError()
}
}
class Empty: Differentiable {}
func testEmpty() {
assertConformsToAdditiveArithmetic(Empty.TangentVector.self)
}
// Test structs with `let` stored properties.
// Derived conformances fail because `mutating func move` requires all stored
// properties to be mutable.
class ImmutableStoredProperties: Differentiable {
var okay: Float
// expected-warning @+1 {{stored property 'nondiff' has no derivative because 'Int' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}} {{3-3=@noDerivative }}
let nondiff: Int
// expected-warning @+1 {{synthesis of the 'Differentiable.move(along:)' requirement for 'ImmutableStoredProperties' requires all stored properties not marked with `@noDerivative` to be mutable; use 'var' instead, or add an explicit '@noDerivative' attribute}} {{3-3=@noDerivative }}
let diff: Float
init() {
okay = 0
nondiff = 0
diff = 0
}
}
func testImmutableStoredProperties() {
_ = ImmutableStoredProperties.TangentVector(okay: 1)
}
class MutableStoredPropertiesWithInitialValue: Differentiable {
var x = Float(1)
var y = Double(1)
}
// Test class with both an empty constructor and memberwise initializer.
class AllMixedStoredPropertiesHaveInitialValue: Differentiable {
// expected-warning @+1 {{synthesis of the 'Differentiable.move(along:)' requirement for 'AllMixedStoredPropertiesHaveInitialValue' requires all stored properties not marked with `@noDerivative` to be mutable; use 'var' instead, or add an explicit '@noDerivative' attribute}} {{3-3=@noDerivative }}
let x = Float(1)
var y = Float(1)
// Memberwise initializer should be `init(y:)` since `x` is immutable.
static func testMemberwiseInitializer() {
_ = AllMixedStoredPropertiesHaveInitialValue()
}
}
/*
class HasCustomConstructor: Differentiable {
var x = Float(1)
var y = Float(1)
// Custom constructor should not affect synthesis.
init(x: Float, y: Float, z: Bool) {}
}
*/
class Simple: Differentiable {
var w: Float
var b: Float
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
func testSimple() {
let simple = Simple(w: 1, b: 1)
let tangent = Simple.TangentVector(w: 1, b: 1)
simple.move(along: tangent)
}
// Test type with mixed members.
class Mixed: Differentiable {
var simple: Simple
var float: Float
init(simple: Simple, float: Float) {
self.simple = simple
self.float = float
}
}
func testMixed(_ simple: Simple, _ simpleTangent: Simple.TangentVector) {
let mixed = Mixed(simple: simple, float: 1)
let tangent = Mixed.TangentVector(simple: simpleTangent, float: 1)
mixed.move(along: tangent)
}
// Test type with manual definition of vector space types to `Self`.
final class VectorSpacesEqualSelf: Differentiable & DummyAdditiveArithmetic {
var w: Float
var b: Float
typealias TangentVector = VectorSpacesEqualSelf
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
/*
extension VectorSpacesEqualSelf : Equatable, AdditiveArithmetic {
static func == (lhs: VectorSpacesEqualSelf, rhs: VectorSpacesEqualSelf) -> Bool {
fatalError()
}
static var zero: VectorSpacesEqualSelf {
fatalError()
}
static func + (lhs: VectorSpacesEqualSelf, rhs: VectorSpacesEqualSelf) -> VectorSpacesEqualSelf {
fatalError()
}
static func - (lhs: VectorSpacesEqualSelf, rhs: VectorSpacesEqualSelf) -> VectorSpacesEqualSelf {
fatalError()
}
}
*/
// Test generic type with vector space types to `Self`.
class GenericVectorSpacesEqualSelf<T>: Differentiable
where T: Differentiable, T == T.TangentVector {
var w: T
var b: T
init(w: T, b: T) {
self.w = w
self.b = b
}
}
func testGenericVectorSpacesEqualSelf() {
let genericSame = GenericVectorSpacesEqualSelf<Double>(w: 1, b: 1)
let tangent = GenericVectorSpacesEqualSelf.TangentVector(w: 1, b: 1)
genericSame.move(along: tangent)
}
// Test nested type.
class Nested: Differentiable {
var simple: Simple
var mixed: Mixed
var generic: GenericVectorSpacesEqualSelf<Double>
init(
simple: Simple, mixed: Mixed, generic: GenericVectorSpacesEqualSelf<Double>
) {
self.simple = simple
self.mixed = mixed
self.generic = generic
}
}
func testNested(
_ simple: Simple, _ mixed: Mixed,
_ genericSame: GenericVectorSpacesEqualSelf<Double>
) {
_ = Nested(simple: simple, mixed: mixed, generic: genericSame)
}
// Test type that does not conform to `AdditiveArithmetic` but whose members do.
// Thus, `Self` cannot be used as `TangentVector` or `TangentVector`.
// Vector space structs types must be synthesized.
// Note: it would be nice to emit a warning if conforming `Self` to
// `AdditiveArithmetic` is possible.
class AllMembersAdditiveArithmetic: Differentiable {
var w: Float
var b: Float
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
// Test type whose properties are not all differentiable.
class DifferentiableSubset: Differentiable {
var w: Float
var b: Float
@noDerivative var flag: Bool
@noDerivative let technicallyDifferentiable: Float = .pi
init(w: Float, b: Float, flag: Bool) {
self.w = w
self.b = b
self.flag = flag
}
}
func testDifferentiableSubset() {
_ = DifferentiableSubset.TangentVector(w: 1, b: 1)
_ = DifferentiableSubset.TangentVector(w: 1, b: 1)
}
// Test nested type whose properties are not all differentiable.
class NestedDifferentiableSubset: Differentiable {
var x: DifferentiableSubset
var mixed: Mixed
@noDerivative var technicallyDifferentiable: Float
init(x: DifferentiableSubset, mixed: Mixed) {
self.x = x
self.mixed = mixed
technicallyDifferentiable = 0
}
}
// Test type that uses synthesized vector space types but provides custom
// method.
class HasCustomMethod: Differentiable {
var simple: Simple
var mixed: Mixed
var generic: GenericVectorSpacesEqualSelf<Double>
init(
simple: Simple, mixed: Mixed, generic: GenericVectorSpacesEqualSelf<Double>
) {
self.simple = simple
self.mixed = mixed
self.generic = generic
}
func move(along direction: TangentVector) {
print("Hello world")
simple.move(along: direction.simple)
mixed.move(along: direction.mixed)
generic.move(along: direction.generic)
}
}
// Test type with user-defined memberwise initializer.
class TF_25: Differentiable {
public var bar: Float
public init(bar: Float) {
self.bar = bar
}
}
// Test user-defined memberwise initializer.
class TF_25_Generic<T: Differentiable>: Differentiable {
public var bar: T
public init(bar: T) {
self.bar = bar
}
}
// Test initializer that is not a memberwise initializer because of stored property name vs parameter label mismatch.
class HasCustomNonMemberwiseInitializer<T: Differentiable>: Differentiable {
var value: T
init(randomLabel value: T) { self.value = value }
}
// Test type with generic environment.
class HasGenericEnvironment<Scalar: FloatingPoint & Differentiable>: Differentiable
{
var x: Float = 0
}
// Test type with generic members that conform to `Differentiable`.
class GenericSynthesizeAllStructs<T: Differentiable>: Differentiable {
var w: T
var b: T
init(w: T, b: T) {
self.w = w
self.b = b
}
}
// Test type in generic context.
class A<T: Differentiable> {
class B<U: Differentiable, V>: Differentiable {
class InGenericContext: Differentiable {
@noDerivative var a: A
var b: B
var t: T
var u: U
init(a: A, b: B, t: T, u: U) {
self.a = a
self.b = b
self.t = t
self.u = u
}
}
}
}
// Test extension.
class Extended {
var x: Float
init(x: Float) {
self.x = x
}
}
extension Extended: Differentiable {}
// Test extension of generic type.
class GenericExtended<T> {
var x: T
init(x: T) {
self.x = x
}
}
extension GenericExtended: Differentiable where T: Differentiable {}
// Test constrained extension of generic type.
class GenericConstrained<T> {
var x: T
init(x: T) {
self.x = x
}
}
extension GenericConstrained: Differentiable
where T: Differentiable {}
final class TF_260<T: Differentiable>: Differentiable & DummyAdditiveArithmetic
{
var x: T.TangentVector
init(x: T.TangentVector) {
self.x = x
}
}
// TF-269: Test crash when differentiation properties have no getter.
// Related to access levels and associated type inference.
// TODO(TF-631): Blocked by class type differentiation support.
// [AD] Unhandled instruction in adjoint emitter: %2 = ref_element_addr %0 : $TF_269, #TF_269.filter // user: %3
// [AD] Diagnosing non-differentiability.
// [AD] For instruction:
// %2 = ref_element_addr %0 : $TF_269, #TF_269.filter // user: %3
/*
public protocol TF_269_Layer: Differentiable & KeyPathIterable
where TangentVector: KeyPathIterable {
associatedtype Input: Differentiable
associatedtype Output: Differentiable
func applied(to input: Input) -> Output
}
public class TF_269 : TF_269_Layer {
public var filter: Float
public typealias Activation = @differentiable (Output) -> Output
@noDerivative public let activation: @differentiable (Output) -> Output
init(filter: Float, activation: @escaping Activation) {
self.filter = filter
self.activation = activation
}
// NOTE: `KeyPathIterable` derived conformances do not yet support class
// types.
public var allKeyPaths: [PartialKeyPath<TF_269>] {
[]
}
public func applied(to input: Float) -> Float {
return input
}
}
*/
// Test errors.
// expected-error @+1 {{class 'MissingInitializer' has no initializers}}
class MissingInitializer: Differentiable {
// expected-note @+1 {{stored property 'w' without initial value prevents synthesized initializers}}
var w: Float
// expected-note @+1 {{stored property 'b' without initial value prevents synthesized initializers}}
var b: Float
}
// Test manually customizing vector space types.
// These should fail. Synthesis is semantically unsupported if vector space
// types are customized.
final class TangentVectorWB: DummyAdditiveArithmetic, Differentiable {
var w: Float
var b: Float
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
// expected-error @+3 {{'Differentiable' requires the types 'VectorSpaceTypeAlias.TangentVector' (aka 'TangentVectorWB') and 'TangentVectorWB.TangentVector' be equivalent}}
// expected-note @+2 {{requirement specified as 'Self.TangentVector' == 'Self.TangentVector.TangentVector' [with Self = VectorSpaceTypeAlias]}}
// expected-error @+1 {{type 'VectorSpaceTypeAlias' does not conform to protocol 'Differentiable'}}
final class VectorSpaceTypeAlias: DummyAdditiveArithmetic, Differentiable {
var w: Float
var b: Float
typealias TangentVector = TangentVectorWB
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
// expected-error @+1 {{type 'VectorSpaceCustomStruct' does not conform to protocol 'Differentiable'}}
final class VectorSpaceCustomStruct: DummyAdditiveArithmetic, Differentiable {
var w: Float
var b: Float
struct TangentVector: AdditiveArithmetic, Differentiable {
var w: Float.TangentVector
var b: Float.TangentVector
typealias TangentVector = VectorSpaceCustomStruct.TangentVector
}
init(w: Float, b: Float) {
self.w = w
self.b = b
}
}
class StaticNoDerivative: Differentiable {
@noDerivative static var s: Bool = true
}
final class StaticMembersShouldNotAffectAnything: DummyAdditiveArithmetic,
Differentiable
{
static var x: Bool = true
static var y: Bool = false
}
class ImplicitNoDerivative: Differentiable {
var a: Float = 0
var b: Bool = true // expected-warning {{stored property 'b' has no derivative because 'Bool' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
}
class ImplicitNoDerivativeWithSeparateTangent: Differentiable {
var x: DifferentiableSubset
var b: Bool = true // expected-warning {{stored property 'b' has no derivative because 'Bool' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}} {{3-3=@noDerivative }}
init(x: DifferentiableSubset) {
self.x = x
}
}
// TF-1018: verify that `@noDerivative` warnings are always silenceable, even
// when the `Differentiable` conformance context is not the nominal type
// declaration.
class ExtensionDifferentiableNoDerivative<T> {
// expected-warning @+2 {{stored property 'x' has no derivative because 'T' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
// expected-warning @+1 {{stored property 'y' has no derivative because 'T' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
var x, y: T
// expected-warning @+1 {{stored property 'nondiff' has no derivative because 'Bool' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
var nondiff: Bool
init() { fatalError() }
}
extension ExtensionDifferentiableNoDerivative: Differentiable {}
class ExtensionDifferentiableNoDerivativeFixed<T> {
@noDerivative var x, y: T
@noDerivative var nondiff: Bool
init() { fatalError() }
}
extension ExtensionDifferentiableNoDerivativeFixed: Differentiable {}
class ConditionalDifferentiableNoDerivative<T> {
var x, y: T
// expected-warning @+1 {{stored property 'nondiff' has no derivative because 'Bool' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
var nondiff: Bool
init() { fatalError() }
}
extension ConditionalDifferentiableNoDerivative: Differentiable
where T: Differentiable {}
class ConditionalDifferentiableNoDerivativeFixed<T> {
var x, y: T
@noDerivative var nondiff: Bool
init() { fatalError() }
}
extension ConditionalDifferentiableNoDerivativeFixed: Differentiable
where T: Differentiable {}
// TF-265: Test invalid initializer (that uses a non-existent type).
class InvalidInitializer: Differentiable {
init(filterShape: (Int, Int, Int, Int), blah: NonExistentType) {} // expected-error {{cannot find type 'NonExistentType' in scope}}
}
// Test memberwise initializer synthesis.
final class NoMemberwiseInitializerExtended<T> {
var value: T
init(_ value: T) {
self.value = value
}
}
extension NoMemberwiseInitializerExtended: Equatable, AdditiveArithmetic,
DummyAdditiveArithmetic
where T: AdditiveArithmetic {}
extension NoMemberwiseInitializerExtended: Differentiable
where T: Differentiable & AdditiveArithmetic {}
// SR-12793: Test interaction with `@differentiable` and `@derivative` type-checking.
class SR_12793: Differentiable {
@differentiable
var x: Float = 0
@differentiable
func method() -> Float { x }
@derivative(of: method)
func vjpMethod() -> (value: Float, pullback: (Float) -> TangentVector) { fatalError() }
// Test usage of synthesized `TangentVector` type.
// This should not produce an error: "reference to invalid associated type 'TangentVector'".
func move(along direction: TangentVector) {}
}
// Test property wrappers.
@propertyWrapper
struct ImmutableWrapper<Value> {
private var value: Value
var wrappedValue: Value { value }
init(wrappedValue: Value) {
self.value = wrappedValue
}
}
@propertyWrapper
struct Wrapper<Value> {
var wrappedValue: Value
}
@propertyWrapper
class ClassWrapper<Value> {
var wrappedValue: Value
init(wrappedValue: Value) { self.wrappedValue = wrappedValue }
}
struct Generic<T> {}
extension Generic: Differentiable where T: Differentiable {}
class WrappedProperties: Differentiable {
// expected-warning @+1 {{synthesis of the 'Differentiable.move(along:)' requirement for 'WrappedProperties' requires 'wrappedValue' in property wrapper 'ImmutableWrapper' to be mutable; add an explicit '@noDerivative' attribute}}
@ImmutableWrapper var immutableInt: Generic<Int> = Generic()
// expected-warning @+1 {{stored property 'mutableInt' has no derivative because 'Generic<Int>' does not conform to 'Differentiable'; add an explicit '@noDerivative' attribute}}
@Wrapper var mutableInt: Generic<Int> = Generic()
@Wrapper var float: Generic<Float> = Generic()
@ClassWrapper var float2: Generic<Float> = Generic()
// SR-13071: Test `@differentiable` wrapped property.
@differentiable @Wrapper var float3: Generic<Float> = Generic()
@noDerivative @ImmutableWrapper var nondiff: Generic<Int> = Generic()
static func testTangentMemberwiseInitializer() {
_ = TangentVector(float: .init(), float2: .init(), float3: .init())
}
}
// Test derived conformances in disallowed contexts.
// expected-error @+2 {{type 'OtherFileNonconforming' does not conform to protocol 'Differentiable'}}
// expected-error @+1 {{implementation of 'Differentiable' cannot be automatically synthesized in an extension in a different file to the type}}
extension OtherFileNonconforming: Differentiable {}
// expected-error @+2 {{type 'GenericOtherFileNonconforming<T>' does not conform to protocol 'Differentiable'}}
// expected-error @+1 {{implementation of 'Differentiable' cannot be automatically synthesized in an extension in a different file to the type}}
extension GenericOtherFileNonconforming: Differentiable {}
| apache-2.0 | d0dedfbb463b19c36c59f7fc01dce285 | 29.854922 | 300 | 0.725217 | 4.091846 | false | true | false | false |
stephentyrone/swift | test/attr/require_explicit_availability.swift | 5 | 3558 | // Test the -require-explicit-availability flag
// REQUIRES: OS=macosx
// RUN: %swiftc_driver -typecheck -parse-stdlib -target x86_64-apple-macosx10.10 -Xfrontend -verify -require-explicit-availability -require-explicit-availability-target "macOS 10.10" %s
// RUN: %swiftc_driver -typecheck -parse-stdlib -target x86_64-apple-macosx10.10 -warnings-as-errors %s
public struct S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}}
public func method() { }
}
public func foo() { bar() } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
@usableFromInline
func bar() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
@available(macOS 10.1, *)
public func ok() { }
@available(macOS, unavailable)
public func unavailableOk() { }
@available(macOS, deprecated: 10.10)
public func missingIntro() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
@available(iOS 9.0, *)
public func missingTargetPlatform() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
func privateFunc() { }
@_alwaysEmitIntoClient
public func alwaysEmitted() { }
@available(macOS 10.1, *)
struct SOk {
public func okMethod() { }
}
precedencegroup MediumPrecedence {}
infix operator + : MediumPrecedence
public func +(lhs: S, rhs: S) -> S { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
public enum E { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
public class C { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
public protocol P { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
private protocol PrivateProto { }
extension S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
public func warnForPublicMembers() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{3-3=@available(macOS 10.10, *)\n }}
}
extension S {
internal func dontWarnWithoutPublicMembers() { }
private func dontWarnWithoutPublicMembers1() { }
}
extension S : P { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
}
extension S : PrivateProto {
}
open class OpenClass { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}}
private class PrivateClass { }
extension PrivateClass { }
| apache-2.0 | 083696dc9878ee49dfab0fc8fe92d8d0 | 49.828571 | 211 | 0.74733 | 4.075601 | false | false | false | false |
liuchungui/BGSwiftDemo | Animation/1、CABasicAnimation/1、CABasicAnimation/ViewController.swift | 1 | 4492 | //
// ViewController.swift
// 1、CABasicAnimation
//
// Created by user on 15/9/13.
// Copyright © 2015年 lcg. All rights reserved.
//
import UIKit
let kTranslateAnimation: String = "kTranslateAnimation"
let kRotationAnimation: String = "kRotationAnimation"
let kBasicAnimationLocation: String = "kBasicAnimationLocation"
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var displayView: UIView!
@IBAction func slid(sender: UISlider) {
}
var _layer: CALayer = CALayer()
override func viewDidLoad() {
super.viewDidLoad()
self.setupLayer()
// Do any additional setup after loading the view, typically from a nib.
}
//TODO: Create Layer -
func setupLayer(){
_layer.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
_layer.backgroundColor = UIColor.redColor().CGColor
self.view.layer.addSublayer(_layer)
}
//TODO: Create Animation -
//添加平移动画
func addTranslateAnimation(point: CGPoint){
let translateAnimation = CABasicAnimation(keyPath: "position")
//完成后不删除
translateAnimation.removedOnCompletion = false
//设置动画执行时间
translateAnimation.duration = 10.0
//设置值
translateAnimation.fromValue = NSValue(CGPoint:_layer.position)
translateAnimation.toValue = NSValue(CGPoint: point)
//设置代理
translateAnimation.delegate = self
// translateAnimation.speed = 10.0
translateAnimation.setValue(NSValue(CGPoint:point), forKey: kBasicAnimationLocation)
//添加动画
_layer.addAnimation(translateAnimation, forKey: kTranslateAnimation)
}
//添加旋转动画
func addRotationAnimation(){
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.removedOnCompletion = false
rotationAnimation.duration = 2.0
rotationAnimation.toValue = NSNumber(double: M_PI*2)
rotationAnimation.repeatCount = 100
//旋转后旋转到原来位置
rotationAnimation.autoreverses = false
_layer.addAnimation(rotationAnimation, forKey: kRotationAnimation)
}
//TODO: Pause and Resume Animation
func pauseAnimation(){
//获取时间偏移量
let timeOffset = _layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
print("mediaTime:\(CACurrentMediaTime()), timeoffset:\(timeOffset)")
//保证暂停时,旋转位置暂停在当前位置
_layer.timeOffset = timeOffset
//设置速度
_layer.speed = 0
}
func resumeAnimation(){
//暂停时的时间偏移量
let pauseTimeOffset = _layer.timeOffset
_layer.timeOffset = 0
//设置开始时间,设置为相对于父layer的相对偏移位置,因为speed为0,所以状态看起来没变化
_layer.beginTime = CACurrentMediaTime() - pauseTimeOffset
//设置速度
_layer.speed = 1
print(_layer.duration)
}
//TODO: Touch method -
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if _layer.animationForKey(kTranslateAnimation) != nil {
if _layer.speed == 0 {
self.resumeAnimation()
}
else{
self.pauseAnimation()
}
}
else{
let touch = touches.first
if let point = touch?.locationInView(self.view) {
self.addTranslateAnimation(point)
self.addRotationAnimation()
}
}
}
//TODO: animation delegate
override func animationDidStart(anim: CAAnimation) {
print("animationDidStart")
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
print("animationDidStop")
//开启事务
CATransaction.begin()
//禁用隐式动画
CATransaction.setDisableActions(true)
//设置位置
_layer.position = anim.valueForKey(kBasicAnimationLocation)!.CGPointValue
//提交事务
CATransaction.commit()
//暂停动画
self.pauseAnimation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 37ae9d68e11f68c2cb081d0a20a814d5 | 30.780303 | 92 | 0.632896 | 4.794286 | false | false | false | false |
docileninja/Calvin-and-Hobbes-Viewer | Viewer/Calvin and Hobbes/Model/ComicDownloader.swift | 1 | 2161 | //
// ComicDownloader.swift
// Calvin and Hobbes
//
// Created by Adam Van Prooyen on 10/1/15.
// Copyright © 2015 Adam Van Prooyen. All rights reserved.
//
import Foundation
import Alamofire
import Timepiece
class ComicDownloader {
static let baseURL = "https://calvinserver.herokuapp.com"
// static let baseURL = "http://localhost:5000"
class func getComic(_ date: Date, completionHandler: @escaping (String?, [Int]?, UIImage?) -> ()) {
let datePart = date.stringFromFormat("YYYY-MM-dd")
Alamofire.request(baseURL + "/comic/" + datePart, method: .get)
.responseJSON { response in
if let json = response.result.value as? [String: AnyObject] {
if let imageUrl = json["url"] as? String, let imageSepsString = json["seps"] as? String {
let imageSeps = imageSepsString.components(separatedBy: " ")
.map{ Int($0)! }
Alamofire.request(imageUrl, method: .get)
.responseData { response in
print(imageSeps)
if let data = response.data {
completionHandler(imageUrl, imageSeps, UIImage(data: data))
} else {
completionHandler(imageUrl, imageSeps, nil)
}
}
} else {
completionHandler(nil, nil, nil)
}
}
}
}
class func searchComics(_ query: String, completionHandler: @escaping ([SearchResult]) -> ()) {
let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
Alamofire.request(baseURL + "/search/" + escapedQuery, method: .get)
.responseJSON { response in
if let results = response.result.value as? [[String: String]] {
completionHandler(results.map({ result in
return SearchResult(date: result["date"]!, snippet: result["text"]!)
}))
}
}
}
}
| mit | cc84ad4ca3d92c583cd0ba33747c4acf | 37.571429 | 108 | 0.535185 | 4.897959 | false | false | false | false |
koroff/Charts | Charts/Classes/Renderers/PieChartRenderer.swift | 2 | 33837 | //
// PieChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class PieChartRenderer: ChartDataRendererBase
{
public weak var chart: PieChartView?
public init(chart: PieChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.chart = chart
}
public override func drawData(context context: CGContext)
{
guard let chart = chart else { return }
let pieData = chart.data
if (pieData != nil)
{
for set in pieData!.dataSets as! [IPieChartDataSet]
{
if set.isVisible && set.entryCount > 0
{
drawDataSet(context: context, dataSet: set)
}
}
}
}
public func calculateMinimumRadiusForSpacedSlice(
center center: CGPoint,
radius: CGFloat,
angle: CGFloat,
arcStartPointX: CGFloat,
arcStartPointY: CGFloat,
startAngle: CGFloat,
sweepAngle: CGFloat) -> CGFloat
{
let angleMiddle = startAngle + sweepAngle / 2.0
// Other point of the arc
let arcEndPointX = center.x + radius * cos((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + radius * sin((startAngle + sweepAngle) * ChartUtils.Math.FDEG2RAD)
// Middle point on the arc
let arcMidPointX = center.x + radius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcMidPointY = center.y + radius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
// This is the base of the contained triangle
let basePointsDistance = sqrt(
pow(arcEndPointX - arcStartPointX, 2) +
pow(arcEndPointY - arcStartPointY, 2))
// After reducing space from both sides of the "slice",
// the angle of the contained triangle should stay the same.
// So let's find out the height of that triangle.
let containedTriangleHeight = (basePointsDistance / 2.0 *
tan((180.0 - angle) / 2.0 * ChartUtils.Math.FDEG2RAD))
// Now we subtract that from the radius
var spacedRadius = radius - containedTriangleHeight
// And now subtract the height of the arc that's between the triangle and the outer circle
spacedRadius -= sqrt(
pow(arcMidPointX - (arcEndPointX + arcStartPointX) / 2.0, 2) +
pow(arcMidPointY - (arcEndPointY + arcStartPointY) / 2.0, 2))
return spacedRadius
}
public func drawDataSet(context context: CGContext, dataSet: IPieChartDataSet)
{
guard let
chart = chart,
data = chart.data,
animator = animator
else {return }
var angle: CGFloat = 0.0
let rotationAngle = chart.rotationAngle
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let entryCount = dataSet.entryCount
var drawAngles = chart.drawAngles
let center = chart.centerCircleBox
let radius = chart.radius
let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled
let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0
var visibleAngleCount = 0
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
if ((abs(e.value) > 0.000001))
{
visibleAngleCount += 1
}
}
let sliceSpace = visibleAngleCount <= 1 ? 0.0 : dataSet.sliceSpace
CGContextSaveGState(context)
for j in 0 ..< entryCount
{
let sliceAngle = drawAngles[j]
var innerRadius = userInnerRadius
guard let e = dataSet.entryForIndex(j) else { continue }
// draw only if the value is greater than zero
if ((abs(e.value) > 0.000001))
{
if (!chart.needsHighlight(xIndex: e.xIndex,
dataSetIndex: data.indexOfDataSet(dataSet)))
{
let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
let sliceSpaceAngleOuter = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * radius)
let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY
var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY
if (sweepAngleOuter < 0.0)
{
sweepAngleOuter = 0.0
}
let arcStartPointX = center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD)
let arcStartPointY = center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD)
let path = CGPathCreateMutable()
CGPathMoveToPoint(
path,
nil,
arcStartPointX,
arcStartPointY)
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
radius,
startAngleOuter * ChartUtils.Math.FDEG2RAD,
sweepAngleOuter * ChartUtils.Math.FDEG2RAD)
if drawInnerArc &&
(innerRadius > 0.0 || accountForSliceSpacing)
{
if accountForSliceSpacing
{
var minSpacedRadius = calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: arcStartPointX,
arcStartPointY: arcStartPointY,
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
if minSpacedRadius < 0.0
{
minSpacedRadius = -minSpacedRadius
}
innerRadius = min(max(innerRadius, minSpacedRadius), radius)
}
let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius)
let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY
var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY
if (sweepAngleInner < 0.0)
{
sweepAngleInner = 0.0
}
let endAngleInner = startAngleInner + sweepAngleInner
CGPathAddLineToPoint(
path,
nil,
center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD),
center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD))
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
innerRadius,
endAngleInner * ChartUtils.Math.FDEG2RAD,
-sweepAngleInner * ChartUtils.Math.FDEG2RAD)
}
else
{
if accountForSliceSpacing
{
let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0
let sliceSpaceOffset =
calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: arcStartPointX,
arcStartPointY: arcStartPointY,
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
let arcEndPointX = center.x + sliceSpaceOffset * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + sliceSpaceOffset * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
CGPathAddLineToPoint(
path,
nil,
arcEndPointX,
arcEndPointY)
}
else
{
CGPathAddLineToPoint(
path,
nil,
center.x,
center.y)
}
}
CGPathCloseSubpath(path)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextEOFillPath(context)
}
}
angle += sliceAngle * phaseX
}
CGContextRestoreGState(context)
}
public override func drawValues(context context: CGContext)
{
guard let
chart = chart,
data = chart.data,
animator = animator
else { return }
let center = chart.centerCircleBox
// get whole the radius
let radius = chart.radius
let rotationAngle = chart.rotationAngle
var drawAngles = chart.drawAngles
var absoluteAngles = chart.absoluteAngles
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var labelRadiusOffset = radius / 10.0 * 3.0
if chart.drawHoleEnabled
{
labelRadiusOffset = (radius - (radius * chart.holeRadiusPercent)) / 2.0
}
let labelRadius = radius - labelRadiusOffset
var dataSets = data.dataSets
let yValueSum = (data as! PieChartData).yValueSum
let drawXVals = chart.isDrawSliceTextEnabled
let usePercentValuesEnabled = chart.usePercentValuesEnabled
var angle: CGFloat = 0.0
var xIndex = 0
CGContextSaveGState(context)
defer { CGContextRestoreGState(context) }
for i in 0 ..< dataSets.count
{
guard let dataSet = dataSets[i] as? IPieChartDataSet else { continue }
let drawYVals = dataSet.isDrawValuesEnabled
if (!drawYVals && !drawXVals)
{
continue
}
let xValuePosition = dataSet.xValuePosition
let yValuePosition = dataSet.yValuePosition
let valueFont = dataSet.valueFont
let lineHeight = valueFont.lineHeight
guard let formatter = dataSet.valueFormatter else { continue }
for j in 0 ..< dataSet.entryCount
{
if (drawXVals && !drawYVals && (j >= data.xValCount || data.xVals[j] == nil))
{
continue
}
guard let e = dataSet.entryForIndex(j) else { continue }
if (xIndex == 0)
{
angle = 0.0
}
else
{
angle = absoluteAngles[xIndex - 1] * phaseX
}
let sliceAngle = drawAngles[xIndex]
let sliceSpace = dataSet.sliceSpace
let sliceSpaceMiddleAngle = sliceSpace / (ChartUtils.Math.FDEG2RAD * labelRadius)
// offset needed to center the drawn text in the slice
let angleOffset = (sliceAngle - sliceSpaceMiddleAngle / 2.0) / 2.0
angle = angle + angleOffset
let transformedAngle = rotationAngle + angle * phaseY
let value = usePercentValuesEnabled ? e.value / yValueSum * 100.0 : e.value
let valueText = formatter.stringFromNumber(value)!
let sliceXBase = cos(transformedAngle * ChartUtils.Math.FDEG2RAD)
let sliceYBase = sin(transformedAngle * ChartUtils.Math.FDEG2RAD)
let drawXOutside = drawXVals && xValuePosition == .OutsideSlice
let drawYOutside = drawYVals && yValuePosition == .OutsideSlice
let drawXInside = drawXVals && xValuePosition == .InsideSlice
let drawYInside = drawYVals && yValuePosition == .InsideSlice
if drawXOutside || drawYOutside
{
let valueLineLength1 = dataSet.valueLinePart1Length
let valueLineLength2 = dataSet.valueLinePart2Length
let valueLinePart1OffsetPercentage = dataSet.valueLinePart1OffsetPercentage
var pt2: CGPoint
var labelPoint: CGPoint
var align: NSTextAlignment
var line1Radius: CGFloat
if chart.drawHoleEnabled
{
line1Radius = (radius - (radius * chart.holeRadiusPercent)) * valueLinePart1OffsetPercentage + (radius * chart.holeRadiusPercent)
}
else
{
line1Radius = radius * valueLinePart1OffsetPercentage
}
let polyline2Length = dataSet.valueLineVariableLength
? labelRadius * valueLineLength2 * abs(sin(transformedAngle * ChartUtils.Math.FDEG2RAD))
: labelRadius * valueLineLength2;
let pt0 = CGPoint(
x: line1Radius * sliceXBase + center.x,
y: line1Radius * sliceYBase + center.y)
let pt1 = CGPoint(
x: labelRadius * (1 + valueLineLength1) * sliceXBase + center.x,
y: labelRadius * (1 + valueLineLength1) * sliceYBase + center.y)
if transformedAngle % 360.0 >= 90.0 && transformedAngle % 360.0 <= 270.0
{
pt2 = CGPoint(x: pt1.x - polyline2Length, y: pt1.y)
align = .Right
labelPoint = CGPoint(x: pt2.x - 5, y: pt2.y - lineHeight)
}
else
{
pt2 = CGPoint(x: pt1.x + polyline2Length, y: pt1.y)
align = .Left
labelPoint = CGPoint(x: pt2.x + 5, y: pt2.y - lineHeight)
}
if dataSet.valueLineColor != nil
{
CGContextSetStrokeColorWithColor(context, dataSet.valueLineColor!.CGColor)
CGContextSetLineWidth(context, dataSet.valueLineWidth);
CGContextMoveToPoint(context, pt0.x, pt0.y)
CGContextAddLineToPoint(context, pt1.x, pt1.y)
CGContextAddLineToPoint(context, pt2.x, pt2.y)
CGContextDrawPath(context, CGPathDrawingMode.Stroke);
}
if drawXOutside && drawYOutside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: labelPoint,
align: align,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
if (j < data.xValCount && data.xVals[j] != nil)
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight),
align: align,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
else if drawXOutside
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight / 2.0),
align: align,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
else if drawYOutside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: CGPoint(x: labelPoint.x, y: labelPoint.y + lineHeight / 2.0),
align: align,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
if drawXInside || drawYInside
{
// calculate the text position
let x = labelRadius * sliceXBase + center.x
let y = labelRadius * sliceYBase + center.y - lineHeight
if drawXInside && drawYInside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: CGPoint(x: x, y: y),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
if j < data.xValCount && data.xVals[j] != nil
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: x, y: y + lineHeight),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
else if drawXInside
{
ChartUtils.drawText(
context: context,
text: data.xVals[j]!,
point: CGPoint(x: x, y: y + lineHeight / 2.0),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
else if drawYInside
{
ChartUtils.drawText(
context: context,
text: valueText,
point: CGPoint(x: x, y: y + lineHeight / 2.0),
align: .Center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
xIndex += 1
}
}
}
public override func drawExtras(context context: CGContext)
{
drawHole(context: context)
drawCenterText(context: context)
}
/// draws the hole in the center of the chart and the transparent circle / hole
private func drawHole(context context: CGContext)
{
guard let
chart = chart,
animator = animator
else { return }
if (chart.drawHoleEnabled)
{
CGContextSaveGState(context)
let radius = chart.radius
let holeRadius = radius * chart.holeRadiusPercent
let center = chart.centerCircleBox
if let holeColor = chart.holeColor
{
if holeColor != NSUIColor.clearColor()
{
// draw the hole-circle
CGContextSetFillColorWithColor(context, chart.holeColor!.CGColor)
CGContextFillEllipseInRect(context, CGRect(x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0))
}
}
// only draw the circle if it can be seen (not covered by the hole)
if let transparentCircleColor = chart.transparentCircleColor
{
if transparentCircleColor != NSUIColor.clearColor() &&
chart.transparentCircleRadiusPercent > chart.holeRadiusPercent
{
let alpha = animator.phaseX * animator.phaseY
let secondHoleRadius = radius * chart.transparentCircleRadiusPercent
// make transparent
CGContextSetAlpha(context, alpha);
CGContextSetFillColorWithColor(context, transparentCircleColor.CGColor)
// draw the transparent-circle
CGContextBeginPath(context)
CGContextAddEllipseInRect(context, CGRect(
x: center.x - secondHoleRadius,
y: center.y - secondHoleRadius,
width: secondHoleRadius * 2.0,
height: secondHoleRadius * 2.0))
CGContextAddEllipseInRect(context, CGRect(
x: center.x - holeRadius,
y: center.y - holeRadius,
width: holeRadius * 2.0,
height: holeRadius * 2.0))
CGContextEOFillPath(context)
}
}
CGContextRestoreGState(context)
}
}
/// draws the description text in the center of the pie chart makes most sense when center-hole is enabled
private func drawCenterText(context context: CGContext)
{
guard let
chart = chart,
centerAttributedText = chart.centerAttributedText
else { return }
if chart.drawCenterTextEnabled && centerAttributedText.length > 0
{
let center = chart.centerCircleBox
let innerRadius = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled ? chart.radius * chart.holeRadiusPercent : chart.radius
let holeRect = CGRect(x: center.x - innerRadius, y: center.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0)
var boundingRect = holeRect
if (chart.centerTextRadiusPercent > 0.0)
{
boundingRect = CGRectInset(boundingRect, (boundingRect.width - boundingRect.width * chart.centerTextRadiusPercent) / 2.0, (boundingRect.height - boundingRect.height * chart.centerTextRadiusPercent) / 2.0)
}
let textBounds = centerAttributedText.boundingRectWithSize(boundingRect.size, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine], context: nil)
var drawingRect = boundingRect
drawingRect.origin.x += (boundingRect.size.width - textBounds.size.width) / 2.0
drawingRect.origin.y += (boundingRect.size.height - textBounds.size.height) / 2.0
drawingRect.size = textBounds.size
CGContextSaveGState(context)
let clippingPath = CGPathCreateWithEllipseInRect(holeRect, nil)
CGContextBeginPath(context)
CGContextAddPath(context, clippingPath)
CGContextClip(context)
centerAttributedText.drawWithRect(drawingRect, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .TruncatesLastVisibleLine], context: nil)
CGContextRestoreGState(context)
}
}
public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight])
{
guard let
chart = chart,
data = chart.data,
animator = animator
else { return }
CGContextSaveGState(context)
let phaseX = animator.phaseX
let phaseY = animator.phaseY
var angle: CGFloat = 0.0
let rotationAngle = chart.rotationAngle
var drawAngles = chart.drawAngles
var absoluteAngles = chart.absoluteAngles
let center = chart.centerCircleBox
let radius = chart.radius
let drawInnerArc = chart.drawHoleEnabled && !chart.drawSlicesUnderHoleEnabled
let userInnerRadius = drawInnerArc ? radius * chart.holeRadiusPercent : 0.0
for i in 0 ..< indices.count
{
// get the index to highlight
let xIndex = indices[i].xIndex
if (xIndex >= drawAngles.count)
{
continue
}
guard let set = data.getDataSetByIndex(indices[i].dataSetIndex) as? IPieChartDataSet else { continue }
if !set.isHighlightEnabled
{
continue
}
let entryCount = set.entryCount
var visibleAngleCount = 0
for j in 0 ..< entryCount
{
guard let e = set.entryForIndex(j) else { continue }
if ((abs(e.value) > 0.000001))
{
visibleAngleCount += 1
}
}
if (xIndex == 0)
{
angle = 0.0
}
else
{
angle = absoluteAngles[xIndex - 1] * phaseX
}
let sliceSpace = visibleAngleCount <= 1 ? 0.0 : set.sliceSpace
let sliceAngle = drawAngles[xIndex]
var innerRadius = userInnerRadius
let shift = set.selectionShift
let highlightedRadius = radius + shift
let accountForSliceSpacing = sliceSpace > 0.0 && sliceAngle <= 180.0
CGContextSetFillColorWithColor(context, set.colorAt(xIndex).CGColor)
let sliceSpaceAngleOuter = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * radius)
let sliceSpaceAngleShifted = visibleAngleCount == 1 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * highlightedRadius)
let startAngleOuter = rotationAngle + (angle + sliceSpaceAngleOuter / 2.0) * phaseY
var sweepAngleOuter = (sliceAngle - sliceSpaceAngleOuter) * phaseY
if (sweepAngleOuter < 0.0)
{
sweepAngleOuter = 0.0
}
let startAngleShifted = rotationAngle + (angle + sliceSpaceAngleShifted / 2.0) * phaseY
var sweepAngleShifted = (sliceAngle - sliceSpaceAngleShifted) * phaseY
if (sweepAngleShifted < 0.0)
{
sweepAngleShifted = 0.0
}
let path = CGPathCreateMutable()
CGPathMoveToPoint(
path,
nil,
center.x + highlightedRadius * cos(startAngleShifted * ChartUtils.Math.FDEG2RAD),
center.y + highlightedRadius * sin(startAngleShifted * ChartUtils.Math.FDEG2RAD))
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
highlightedRadius,
startAngleShifted * ChartUtils.Math.FDEG2RAD,
sweepAngleShifted * ChartUtils.Math.FDEG2RAD)
var sliceSpaceRadius: CGFloat = 0.0
if accountForSliceSpacing
{
sliceSpaceRadius = calculateMinimumRadiusForSpacedSlice(
center: center,
radius: radius,
angle: sliceAngle * phaseY,
arcStartPointX: center.x + radius * cos(startAngleOuter * ChartUtils.Math.FDEG2RAD),
arcStartPointY: center.y + radius * sin(startAngleOuter * ChartUtils.Math.FDEG2RAD),
startAngle: startAngleOuter,
sweepAngle: sweepAngleOuter)
}
if drawInnerArc &&
(innerRadius > 0.0 || accountForSliceSpacing)
{
if accountForSliceSpacing
{
var minSpacedRadius = sliceSpaceRadius
if minSpacedRadius < 0.0
{
minSpacedRadius = -minSpacedRadius
}
innerRadius = min(max(innerRadius, minSpacedRadius), radius)
}
let sliceSpaceAngleInner = visibleAngleCount == 1 || innerRadius == 0.0 ?
0.0 :
sliceSpace / (ChartUtils.Math.FDEG2RAD * innerRadius)
let startAngleInner = rotationAngle + (angle + sliceSpaceAngleInner / 2.0) * phaseY
var sweepAngleInner = (sliceAngle - sliceSpaceAngleInner) * phaseY
if (sweepAngleInner < 0.0)
{
sweepAngleInner = 0.0
}
let endAngleInner = startAngleInner + sweepAngleInner
CGPathAddLineToPoint(
path,
nil,
center.x + innerRadius * cos(endAngleInner * ChartUtils.Math.FDEG2RAD),
center.y + innerRadius * sin(endAngleInner * ChartUtils.Math.FDEG2RAD))
CGPathAddRelativeArc(
path,
nil,
center.x,
center.y,
innerRadius,
endAngleInner * ChartUtils.Math.FDEG2RAD,
-sweepAngleInner * ChartUtils.Math.FDEG2RAD)
}
else
{
if accountForSliceSpacing
{
let angleMiddle = startAngleOuter + sweepAngleOuter / 2.0
let arcEndPointX = center.x + sliceSpaceRadius * cos(angleMiddle * ChartUtils.Math.FDEG2RAD)
let arcEndPointY = center.y + sliceSpaceRadius * sin(angleMiddle * ChartUtils.Math.FDEG2RAD)
CGPathAddLineToPoint(
path,
nil,
arcEndPointX,
arcEndPointY)
}
else
{
CGPathAddLineToPoint(
path,
nil,
center.x,
center.y)
}
}
CGPathCloseSubpath(path)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextEOFillPath(context)
}
CGContextRestoreGState(context)
}
}
| apache-2.0 | 0688eca77422451f1959384e608e54bf | 40.214373 | 220 | 0.477111 | 6.030476 | false | false | false | false |
radvansky-tomas/NutriFacts | nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Components/ChartYAxis.swift | 3 | 6585 | //
// ChartYAxis.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
/// Class representing the y-axis labels settings and its entries.
/// Be aware that not all features the YLabels class provides are suitable for the RadarChart.
/// Customizations that affect the value range of the axis need to be applied before setting data for the chart.
public class ChartYAxis: ChartAxisBase
{
@objc
public enum YAxisLabelPosition: Int
{
case OutsideChart
case InsideChart
}
/// Enum that specifies the axis a DataSet should be plotted against, either Left or Right.
@objc
public enum AxisDependency: Int
{
case Left
case Right
}
public var entries = [Float]()
public var entryCount: Int { return entries.count; }
/// the number of y-label entries the y-labels should have, default 6
private var _labelCount = Int(6)
/// indicates if the top y-label entry is drawn or not
public var drawTopYLabelEntryEnabled = true
/// if true, the y-labels show only the minimum and maximum value
public var showOnlyMinMaxEnabled = false
/// flag that indicates if the axis is inverted or not
public var inverted = false
/// if true, the y-label entries will always start at zero
public var startAtZeroEnabled = true
/// the formatter used to customly format the y-labels
public var valueFormatter: NSNumberFormatter?
/// the formatter used to customly format the y-labels
internal var _defaultValueFormatter = NSNumberFormatter()
/// A custom minimum value for this axis.
/// If set, this value will not be calculated automatically depending on the provided data.
/// Use resetcustomAxisMin() to undo this.
/// Do not forget to set startAtZeroEnabled = false if you use this method.
/// Otherwise, the axis-minimum value will still be forced to 0.
public var customAxisMin = Float.NaN
/// Set a custom maximum value for this axis.
/// If set, this value will not be calculated automatically depending on the provided data.
/// Use resetcustomAxisMax() to undo this.
public var customAxisMax = Float.NaN
/// axis space from the largest value to the top in percent of the total axis range
public var spaceTop = CGFloat(0.1)
/// axis space from the smallest value to the bottom in percent of the total axis range
public var spaceBottom = CGFloat(0.1)
public var axisMaximum = Float(0)
public var axisMinimum = Float(0)
/// the total range of values this axis covers
public var axisRange = Float(0)
/// the position of the y-labels relative to the chart
public var labelPosition = YAxisLabelPosition.OutsideChart
/// the side this axis object represents
private var _axisDependency = AxisDependency.Left
public override init()
{
super.init();
_defaultValueFormatter.maximumFractionDigits = 1;
_defaultValueFormatter.minimumFractionDigits = 1;
_defaultValueFormatter.usesGroupingSeparator = true;
}
public init(position: AxisDependency)
{
super.init();
_axisDependency = position;
_defaultValueFormatter.maximumFractionDigits = 1;
_defaultValueFormatter.minimumFractionDigits = 1;
_defaultValueFormatter.usesGroupingSeparator = true;
}
public var axisDependency: AxisDependency
{
return _axisDependency;
}
/// the number of label entries the y-axis should have
/// max = 25,
/// min = 2,
/// default = 6,
/// be aware that this number is not fixed and can only be approximated
public var labelCount: Int
{
get
{
return _labelCount;
}
set
{
_labelCount = newValue;
if (_labelCount > 25)
{
_labelCount = 25;
}
if (_labelCount < 2)
{
_labelCount = 2;
}
}
}
/// By calling this method, any custom minimum value that has been previously set is reseted, and the calculation is done automatically.
public func resetcustomAxisMin()
{
customAxisMin = Float.NaN;
}
/// By calling this method, any custom maximum value that has been previously set is reseted, and the calculation is done automatically.
public func resetcustomAxisMax()
{
customAxisMax = Float.NaN;
}
public func requiredSize() -> CGSize
{
var label = getLongestLabel() as NSString;
var size = label.sizeWithAttributes([NSFontAttributeName: labelFont]);
size.width += xOffset * 2.0;
size.height += yOffset * 2.0;
return size;
}
public override func getLongestLabel() -> String
{
var longest = "";
for (var i = 0; i < entries.count; i++)
{
var text = getFormattedLabel(i);
if (longest.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) < text.lengthOfBytesUsingEncoding(NSUTF16StringEncoding))
{
longest = text;
}
}
return longest;
}
/// Returns the formatted y-label at the specified index. This will either use the auto-formatter or the custom formatter (if one is set).
public func getFormattedLabel(index: Int) -> String
{
if (index < 0 || index >= entries.count)
{
return "";
}
return (valueFormatter ?? _defaultValueFormatter).stringFromNumber(entries[index])!;
}
/// Returns true if this axis needs horizontal offset, false if no offset is needed.
public var needsOffset: Bool
{
if (isEnabled && isDrawLabelsEnabled && labelPosition == .OutsideChart)
{
return true;
}
else
{
return false;
}
}
public var isInverted: Bool { return inverted; }
public var isStartAtZeroEnabled: Bool { return startAtZeroEnabled; }
public var isShowOnlyMinMaxEnabled: Bool { return showOnlyMinMaxEnabled; }
public var isDrawTopYLabelEntryEnabled: Bool { return drawTopYLabelEntryEnabled; }
} | gpl-2.0 | ff1f57978de4c7efc5c11dc337c02323 | 30.066038 | 142 | 0.629157 | 5.104651 | false | false | false | false |
DevaLee/LYCSwiftDemo | LYCSwiftDemo/Classes/Component/Extension/LYCMAttributStingExtension.swift | 1 | 3178 | //
// LYCMAttributStingExtension.swift
// LYCSwiftDemo
//
// Created by 李玉臣 on 2017/6/17.
// Copyright © 2017年 zsc. All rights reserved.
//
import UIKit
import Kingfisher
class LYCMAttributStingExtension: NSObject {
}
extension LYCMAttributStingExtension{
/*进入或者离开房间*/
class func userJoinLeaveRoom(userName : String , isJoinRoom : Bool) -> NSMutableAttributedString{
let roomStr = isJoinRoom ? " :进入房间" : " :离开房间"
let joinText = NSMutableAttributedString(string: userName + roomStr)
joinText.addAttributes([NSForegroundColorAttributeName : UIColor.themeColor()], range: NSMakeRange(0, userName.characters.count))
return joinText
}
/*发送一段文字*/
class func userSendMsg(userName : String , chatMsg : String) -> NSMutableAttributedString{
let msg = userName + ":" + chatMsg
let attriChat = NSMutableAttributedString(string: msg)
attriChat.addAttributes([NSForegroundColorAttributeName : UIColor.themeColor()], range: NSMakeRange(0, userName.characters.count))
let pattern = "\\[.*?\\]"
let regex = try? NSRegularExpression(pattern: pattern)
guard let regexResult = regex?.matches(in: msg, range: NSMakeRange(0, msg.characters.count)) else {
return attriChat
}
for i in (0..<regexResult.count).reversed() {
let result = regexResult[i]
let emotionName = (msg as NSString).substring(with: result.range)
let emotionImage = UIImage(named: emotionName)
//创建一个富文本
let attachText = NSTextAttachment()
attachText.image = emotionImage
let font = UIFont.systemFont(ofSize: 15)
attachText.bounds = CGRect(x: 0, y: -3, width:font.lineHeight , height: font.lineHeight)
let emoAttributeString = NSAttributedString(attachment: attachText)
// 替换文字为相对应的表情图片
attriChat.replaceCharacters(in: result.range, with: emoAttributeString)
}
return attriChat
}
/*发送礼物*/
class func sendGif(userName : String , gifUrl : String , gifName : String ) -> NSMutableAttributedString{
let msg = userName + " 送出 " + gifName
let mAttriMsg = NSMutableAttributedString(string: msg)
mAttriMsg.addAttributes([NSForegroundColorAttributeName : UIColor.themeColor()], range: NSMakeRange(0, userName.characters.count))
let range = ( msg as NSString).range(of: gifName)
mAttriMsg.addAttributes([NSForegroundColorAttributeName : UIColor.brown], range: range)
guard let gifImage = KingfisherManager.shared.cache.retrieveImageInMemoryCache(forKey: gifUrl) else {
return mAttriMsg
}
let textAttach = NSTextAttachment()
textAttach.image = gifImage
textAttach.bounds = CGRect(x: 0, y: 0, width: 80, height: 80)
let gifAttri = NSAttributedString(attachment: textAttach)
mAttriMsg.append(gifAttri)
return mAttriMsg
}
}
| mit | 6bd2e2828a9a3d8f0d9dbb686ed243e3 | 37.898734 | 138 | 0.647901 | 4.545858 | false | false | false | false |
FUKUZAWA-Tadashi/FHCCommander | fhcc/State.swift | 1 | 7267 | //
// State.swift
// fhcc
//
// Created by 福澤 正 on 2014/06/25.
// Copyright (c) 2014年 Fukuzawa Technology. All rights reserved.
//
import Foundation
class State {
// 測位精度がこれより低ければ(大きければ)、その位置情報は捨てる
class var ACCURACY_LIMIT: Double { return 100.0 }
private let USER_DEFAULTS_KEY = "FHC_State"
var fhcAddress: String
var mailAddr: String
var password: String
var homeLatitude: Double
var homeLongitude: Double
var homeRegionRadius: Double
var farRegionRadius: Double
var homeSSID: String
var fhcSecret: String
var fhcOfficialSite: String
var applianceOfOutgo: String
var actionOfOutgo: String
var applianceOfReturnHome: String
var actionOfReturnHome: String
var sensorUpdateInterval: Int
var actionsDict: Dictionary<String, [String]>
var judgeUsingLan: Bool
class var VOICE_COMMAND: String { return "< 音声コマンド >" }
class var ACTIONS_DICT_DEFAULTS: Dictionary<String, [String]> {
return [
VOICE_COMMAND : [
"いってきます", "ただいま"
],
"家電1" : [
"すいっちおん", "でんげんきって"
],
"家電2" : [
"でんげんいれて", "すいっちおふ"
]
]
}
private let KEY_FHC_ADDRESS = "fhcAddress"
private let KEY_MAIL_ADDR = "mailAddr"
private let KEY_PASSWORD = "password"
private let KEY_HOME_LATITUDE = "homeLatitude"
private let KEY_HOME_LONGITUDE = "homeLongitude"
private let KEY_HOME_REGION_RADIUS = "homeRegionRadius"
private let KEY_FAR_REGION_RADIUS = "farRegionRadius"
private let KEY_HOME_SSID = "homeSSID"
private let KEY_FHC_SECRET = "fhcSecret"
private let KEY_FHC_OFFICIAL_SITE = "fhcOfficialSite"
private let KEY_APPLIANCE_OF_OUTGO = "applianceOfOutgo"
private let KEY_ACTION_OF_OUTGO = "actionOfOutgo"
private let KEY_APPLIANCE_OF_RETURN_HOME = "applianceOfReturnHome"
private let KEY_ACTION_OF_RETURN_HOME = "actionOfReturnHome"
private let KEY_SENSOR_UPDATE_INTERVAL = "sensorUpdateInterval"
private let KEY_JUDGE_USING_LAN = "judgeUsingLan"
private let KEY_AD_KEYS = "ad_keys"
private let KEY_AD_VAL = "ad_val_"
init () {
fhcAddress = "fhc.local"
mailAddr = ""
password = ""
homeLatitude = 0.0
homeLongitude = 0.0
homeRegionRadius = 20.0
farRegionRadius = 200.0
homeSSID = ""
fhcSecret = ""
fhcOfficialSite = "fhc.rti-giken.jp"
applianceOfOutgo = ""
actionOfOutgo = ""
applianceOfReturnHome = ""
actionOfReturnHome = ""
sensorUpdateInterval = 30
actionsDict = State.ACTIONS_DICT_DEFAULTS
judgeUsingLan = true
}
func loadFromUserDefaults () -> Bool {
var defaults = NSUserDefaults.standardUserDefaults()
var failed = false
func chk_load_string(key:String) -> String! {
let x = defaults.stringForKey(key)
if x == nil {
NSLog("load state failed on '\(key)'")
failed = true
}
return x
}
func chk_load_object(key:String) -> AnyObject! {
let x: AnyObject! = defaults.objectForKey(key)
if x == nil {
NSLog("load state failed on '\(key)'")
failed = true
}
return x
}
func chk_load_string_array(key:String) -> [String]! {
let x: [AnyObject]! = defaults.stringArrayForKey(key)
if x == nil {
NSLog("load state failed on '\(key)'")
failed = true
return nil
}
return x as [String]
}
fhcAddress = chk_load_string(KEY_FHC_ADDRESS) ?? "fhc.local"
mailAddr = chk_load_string(KEY_MAIL_ADDR) ?? ""
password = chk_load_string(KEY_PASSWORD) ?? ""
homeLatitude = defaults.doubleForKey(KEY_HOME_LATITUDE)
homeLongitude = defaults.doubleForKey(KEY_HOME_LONGITUDE)
homeRegionRadius = defaults.doubleForKey(KEY_HOME_REGION_RADIUS)
farRegionRadius = defaults.doubleForKey(KEY_FAR_REGION_RADIUS)
homeSSID = chk_load_string(KEY_HOME_SSID) ?? ""
fhcSecret = chk_load_string(KEY_FHC_SECRET) ?? ""
fhcOfficialSite = chk_load_string(KEY_FHC_OFFICIAL_SITE) ?? "fhc.rti-giken.jp"
applianceOfOutgo = chk_load_string(KEY_APPLIANCE_OF_OUTGO) ?? ""
actionOfOutgo = chk_load_string(KEY_ACTION_OF_OUTGO) ?? ""
applianceOfReturnHome = chk_load_string(KEY_APPLIANCE_OF_RETURN_HOME) ?? ""
actionOfReturnHome = chk_load_string(KEY_ACTION_OF_RETURN_HOME) ?? ""
if homeRegionRadius == 0.0 { homeRegionRadius = 20.0 }
if farRegionRadius == 0.0 { farRegionRadius = 200.0 }
if (failed) {
sensorUpdateInterval = 30
judgeUsingLan = true
} else {
sensorUpdateInterval = defaults.integerForKey(KEY_SENSOR_UPDATE_INTERVAL)
judgeUsingLan = defaults.boolForKey(KEY_JUDGE_USING_LAN)
}
var adict = Dictionary<String, [String]>()
let ad_keys = chk_load_string_array(KEY_AD_KEYS)
if ad_keys != nil {
for (i,k) in enumerate(ad_keys!) {
let x = chk_load_string_array(KEY_AD_VAL + "\(i)")
if x != nil {
adict[k] = x
}
}
}
if adict.count > 0 { actionsDict = adict }
return !failed
}
func saveToUserDefaults () {
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(fhcAddress, forKey: KEY_FHC_ADDRESS)
defaults.setObject(mailAddr, forKey: KEY_MAIL_ADDR)
defaults.setObject(password, forKey: KEY_PASSWORD)
defaults.setDouble(homeLatitude, forKey: KEY_HOME_LATITUDE)
defaults.setDouble(homeLongitude, forKey: KEY_HOME_LONGITUDE)
defaults.setDouble(homeRegionRadius, forKey: KEY_HOME_REGION_RADIUS)
defaults.setDouble(farRegionRadius, forKey: KEY_FAR_REGION_RADIUS)
defaults.setObject(homeSSID, forKey: KEY_HOME_SSID)
defaults.setObject(fhcSecret, forKey: KEY_FHC_SECRET)
defaults.setObject(fhcOfficialSite, forKey: KEY_FHC_OFFICIAL_SITE)
defaults.setObject(applianceOfOutgo, forKey: KEY_APPLIANCE_OF_OUTGO)
defaults.setObject(actionOfOutgo, forKey: KEY_ACTION_OF_OUTGO)
defaults.setObject(applianceOfReturnHome, forKey: KEY_APPLIANCE_OF_RETURN_HOME)
defaults.setObject(actionOfReturnHome, forKey: KEY_ACTION_OF_RETURN_HOME)
defaults.setInteger(sensorUpdateInterval, forKey: KEY_SENSOR_UPDATE_INTERVAL)
defaults.setBool(judgeUsingLan, forKey: KEY_JUDGE_USING_LAN)
let ad_keys = actionsDict.keys.array
defaults.setObject(ad_keys.map{NSString(string:$0)}, forKey: KEY_AD_KEYS)
for (i,k) in enumerate(ad_keys) {
let ad_val = actionsDict[k]!.map{NSString(string:$0)}
defaults.setObject(ad_val, forKey: KEY_AD_VAL + "\(i)")
}
defaults.synchronize()
}
} | mit | 06d7c9b66e9e4860bfb6ff93966ddca3 | 36.03125 | 87 | 0.612463 | 3.673902 | false | false | false | false |
Jaberer/Poll_io | iOS/WUHack/WUHack/DataViewController.swift | 1 | 3534 | //
// ViewController.swift
// WUHack
//
// Created by Calvin on 9/19/15.
// Copyright (c) 2015 Calvin. All rights reserved.
//
import UIKit
import Parse
import Bolts
class DataViewController: UIViewController {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var entityLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// var query = PFQuery(className: "Channel")
// var channel = query.getFirstObject()
// var object = PFObject(className: "Poll")
// object.setObject(true, forKey: "open")
// object.setObject(channel!, forKey: "channel")
// object.setObject("is joseph dumb?", forKey: "topic")
// object.setObject(PFUser.currentUser()!, forKey: "submitter")
// object.save()
//
// PFUser.currentUser()!.addObject(channel!.objectId!, forKey: "Channels")
// PFUser.currentUser()!.save()
}
override func viewDidAppear(animated: Bool) {
loadQuestion({
(entity, alchemy, error) -> Void in
if error == nil
{
var question : String = alchemy!.objectForKey("body") as! String
self.questionLabel.text = question
var entityName : String = entity!.objectForKey("name") as! String
var entityScore : Double = (entity!.objectForKey("score") as! NSString).doubleValue
self.entityLabel.text = self.entitySummary(entityName, score: entityScore)
}
})
}
func entitySummary(name: String, score: Double) -> String
{
var scoreDescription : String = ""
if score < -0.75
{
scoreDescription = "terrible"
}
else if score < -0.4
{
scoreDescription = "bad"
}
else if score < -0.1
{
scoreDescription = "meh, dubious"
}
else if score < 0.1
{
scoreDescription = "neutral"
}
else if score < 0.4
{
scoreDescription = "meh, ok"
}
else if score < 0.75
{
scoreDescription = "good"
}
else
{
scoreDescription = "ecstatic"
}
return "Attitude towards \(name) is \(scoreDescription)."
}
func loadQuestion(completion: (PFObject?, PFObject?, NSError?) -> Void)
{
var query = PFQuery(className: "Entities")
query.orderByDescending("createdAt")
query.getFirstObjectInBackgroundWithBlock({
(object, error) -> Void in
if error == nil
{
if object != nil
{
var alchemyId : String = object!.objectForKey("Alchemy") as! String
var alchemyQuery : PFQuery = PFQuery(className: "Alchemy")
var alchemy : PFObject? = alchemyQuery.getObjectWithId(alchemyId)
completion(object, alchemy, nil)
}
else
{
println()
completion(nil, nil, nil)
}
}
else
{
completion(nil, nil, nil)
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-2.0 | bb0d7533274aa7b2c498003336349602 | 27.272 | 99 | 0.508489 | 4.935754 | false | false | false | false |
fluidsonic/JetPack | Sources/UI/PartialSize.swift | 1 | 1907 | import CoreGraphics
public struct PartialSize: CustomDebugStringConvertible, Hashable {
public var height: CGFloat?
public var width: CGFloat?
public init(width: CGFloat? = nil, height: CGFloat? = nil) {
self.height = height
self.width = width
}
public init(square: CGFloat?) {
self.height = square
self.width = square
}
public var debugDescription: String {
return "(\(width?.description ?? "nil"), \(height?.description ?? "nil"))"
}
public func toSize() -> CGSize? {
guard let height = height, let width = width else {
return nil
}
return CGSize(width: width, height: height)
}
}
extension CGSize {
public func coerced(atLeast minimum: PartialSize) -> CGSize {
var coercedSize = self
if let minimumWidth = minimum.width {
coercedSize.width = coercedSize.width.coerced(atLeast: minimumWidth)
}
if let minimumHeight = minimum.height {
coercedSize.height = coercedSize.height.coerced(atLeast: minimumHeight)
}
return coercedSize
}
public func coerced(atMost maximum: PartialSize) -> CGSize {
var coercedSize = self
if let maximumWidth = maximum.width {
coercedSize.width = coercedSize.width.coerced(atMost: maximumWidth)
}
if let maximumHeight = maximum.height {
coercedSize.height = coercedSize.height.coerced(atMost: maximumHeight)
}
return coercedSize
}
public func coerced(atLeast minimum: PartialSize, atMost maximum: PartialSize) -> CGSize {
return coerced(atMost: maximum).coerced(atLeast: minimum)
}
public func coerced(atLeast minimum: CGSize, atMost maximum: PartialSize) -> CGSize {
return coerced(atMost: maximum).coerced(atLeast: minimum)
}
public func coerced(atLeast minimum: PartialSize, atMost maximum: CGSize) -> CGSize {
return coerced(atMost: maximum).coerced(atLeast: minimum)
}
public func toPartial() -> PartialSize {
return PartialSize(width: width, height: height)
}
}
| mit | 009548398adc01b6020512b3e545dfb3 | 21.702381 | 91 | 0.721028 | 3.746562 | false | false | false | false |
fluidsonic/JetPack | Sources/UI/z_ImageView+MKMapSnapshotSource.swift | 1 | 4005 | // File name prefixed with z_ to avoid compiler crash related to type extensions, nested types and order of Swift source files.
import MapKit
public extension ImageView {
struct MKMapSnapshotSource: ImageView.Source, Equatable {
private var options: MKMapSnapshotter.Options
public init(options: MKMapSnapshotter.Options = MKMapSnapshotter.Options()) {
self.options = options
ensureUniqueOptions()
}
public var camera: MKMapCamera {
get { return options.camera }
set {
if newValue != options.camera {
ensureUniqueOptions()
options.camera = newValue
}
}
}
public func createSession() -> ImageView.Session? {
return MKMapSnapshotSourceSession(options: options)
}
private mutating func ensureUniqueOptions() {
if !isKnownUniquelyReferenced(&options) {
options = options.copy() as! MKMapSnapshotter.Options
}
}
public var mapRect: MKMapRect {
get { return options.mapRect }
set {
if newValue != options.mapRect {
ensureUniqueOptions()
options.mapRect = newValue
}
}
}
public var mapType: MKMapType {
get { return options.mapType }
set {
if newValue != options.mapType {
ensureUniqueOptions()
options.mapType = newValue
}
}
}
public var region: MKCoordinateRegion {
get { return options.region }
set {
if newValue != options.region {
ensureUniqueOptions()
options.region = newValue
}
}
}
public var showsBuildings: Bool {
get { return options.showsBuildings }
set {
if newValue != options.showsBuildings {
ensureUniqueOptions()
options.showsBuildings = newValue
}
}
}
public var showsPointsOfInterest: Bool {
get { return options.showsPointsOfInterest }
set {
if newValue != options.showsPointsOfInterest {
ensureUniqueOptions()
options.showsPointsOfInterest = newValue
}
}
}
public static func == (a: MKMapSnapshotSource, b: MKMapSnapshotSource) -> Bool {
let a = a.options
let b = b.options
return a.camera == b.camera
&& a.mapRect == b.mapRect
&& a.mapType == b.mapType
&& a.region == b.region
&& a.showsBuildings == b.showsBuildings
&& a.showsPointsOfInterest == b.showsPointsOfInterest
}
}
}
private final class MKMapSnapshotSourceSession: ImageView.Session {
private var lastRequestedScale = CGFloat(0)
private var lastRequestedSize = CGSize.zero
private var listener: ImageView.SessionListener?
private var options: MKMapSnapshotter.Options
private var snapshotter: MKMapSnapshotter?
init(options: MKMapSnapshotter.Options) {
self.options = options
}
func imageViewDidChangeConfiguration(_ imageView: ImageView) {
startOrRestartRequest(for: imageView)
}
private func startOrRestartRequest(for imageView: ImageView) {
let scale = imageView.optimalImageScale
let size = imageView.optimalImageSize
guard scale != lastRequestedScale || size != lastRequestedSize else {
return
}
stopRequest()
startRequest(size: size, scale: scale)
}
private func startRequest(size: CGSize, scale: CGFloat) {
precondition(self.snapshotter == nil)
self.lastRequestedScale = scale
self.lastRequestedSize = size
options.scale = scale
options.size = size
let snapshotter = MKMapSnapshotter(options: options)
self.snapshotter = snapshotter
snapshotter.start { snapshot, _ in
self.snapshotter = nil
guard let snapshot = snapshot else {
return
}
onMainQueue {
self.listener?.sessionDidRetrieveImage(snapshot.image)
}
}
}
func startRetrievingImageForImageView(_ imageView: ImageView, listener: ImageView.SessionListener) {
precondition(self.listener == nil)
self.listener = listener
self.startOrRestartRequest(for: imageView)
}
private func stopRequest() {
guard let snapshotter = self.snapshotter else {
return
}
snapshotter.cancel()
self.snapshotter = nil
}
func stopRetrievingImage() {
listener = nil
stopRequest()
}
}
| mit | 92831d1f035bb5ad232987d6472c3423 | 19.433673 | 127 | 0.702372 | 3.810657 | false | false | false | false |
illuminati-fin/LANScan-iOS | LANScan/IPAddress.swift | 1 | 1632 | //
// IPAddress.swift
// TestApp
//
// Created by Ville Välimaa on 20/01/2017.
// Copyright © 2017 Ville Välimaa. All rights reserved.
//
class IPAddress {
static func getWiFiAddress() -> String? {
var address : String?
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return nil }
guard let firstAddr = ifaddr else { return nil }
// For each interface ...
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let interface = ifptr.pointee
// Check for IPv4 or IPv6 interface:
let addrFamily = interface.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
// Check interface name:
let name = String(cString: interface.ifa_name)
if name == "en0" {
// Convert interface address to a human readable string:
var addr = interface.ifa_addr.pointee
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(&addr, socklen_t(interface.ifa_addr.pointee.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
return address
}
}
| mit | 18e71a6f925eb5f0d839dc18a4039113 | 36.022727 | 84 | 0.522406 | 4.563025 | false | false | false | false |
SnowyWhite/RequestManager | Example/RequestManager/ViewController.swift | 1 | 1763 | //
// ViewController.swift
// RequestManager
//
// Created by Nick Kibish on 07/18/2016.
// Copyright (c) 2016 Nick Kibish. All rights reserved.
//
import UIKit
import RequestManager
class ViewController: UIViewController {
@IBOutlet var requestStatulLabel: UILabel!
@IBOutlet var requestURLTF: UITextField!
@IBOutlet var baseURLTF: UITextField!
@IBAction func makeRequest(_ sender: AnyObject) {
requestStatulLabel.text = "Loading..."
requestStatulLabel.textColor = UIColor.lightGray
do {
let request = try RequestManager.sharedInstance.request(path: requestURLTF.text!, method: .get, parameters: nil)
RequestManager.sharedInstance.make(request: request, success: { (_, _) in
self.requestStatulLabel.textColor = UIColor.green
self.requestStatulLabel.text = "OK"
}, failure: { (_, _, _) in
self.requestStatulLabel.textColor = UIColor.red
self.requestStatulLabel.text = "Error"
})
} catch let error as RequestManagerError {
switch error {
case .isntReachable:
Log.error("isn't reachable")
case .needsConnection:
Log.error("Needs Connection")
case .wrongURL:
Log.error("Wrong URL")
case .unknownError(_):
Log.error("Unknown error")
default:
Log.error("Other Error")
}
} catch {
Log.error("Error")
}
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | df30ad60add99739e6492e52015e5d24 | 31.054545 | 124 | 0.590471 | 4.81694 | false | false | false | false |
slimane-swift/WS | Sources/Client.swift | 1 | 4768 | //
// WebsocketClient.swift
// HangerSocket
//
// Created by Yuki Takei on 5/5/16.
// Copyright © 2016 MikeTOKYO. All rights reserved.
//
// Client.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 HTTP
import HTTPParser
import AsyncHTTPSerializer
public enum ClientError: Error {
case unsupportedScheme
case hostRequired
case responseNotWebsocket
}
public struct WebSocketClient {
let connection: TCPClient
public let uri: URI
public let loop: Loop
public init(loop: Loop = Loop.defaultLoop, uri: URI, onConnect: @escaping ((Void) throws -> WebSocket) -> Void) {
self.uri = uri
let request = Request(uri: uri)
self.loop = loop
self.connection = TCPClient(loop: loop, uri: request.uri)
connect(onConnect: onConnect)
}
private func connect(onConnect: @escaping ((Void) throws -> WebSocket) -> Void){
do {
let key = try Base64.encode(Crypto.randomBytesSync(16))
let headers: Headers = [
"Connection": "Upgrade",
"Upgrade": "websocket",
"Sec-WebSocket-Version": "13",
"Sec-WebSocket-Key": key,
]
let request = Request(method: .get, uri: self.uri, headers: headers)
// callback hell....
try connection.open { getConnection in
do {
let connection = try getConnection()
AsyncHTTPSerializer.RequestSerializer(stream: connection).serialize(request) { _ in }
let parser = ResponseParser()
connection.receive(upTo: 2048, timingOut: .never) {
do {
if let response = try parser.parse(data: try $0()) {
self.onConnect(request: request, response: response, key: key, completion: onConnect)
}
} catch {
onConnect {
throw error
}
}
}
} catch {
onConnect {
throw error
}
}
}
} catch {
onConnect {
throw error
}
}
}
private func onConnect(request: Request, response: Response, key: String, completion: @escaping ((Void) throws -> WebSocket) -> Void){
guard response.status == .switchingProtocols && response.isWebSocket else {
return completion {
throw ClientError.responseNotWebsocket
}
}
WebSocket.accept(key: key) { result in
let accept = response.webSocketAccept
completion {
guard try accept == result() else {
throw ClientError.responseNotWebsocket
}
let socket = WebSocket(stream: self.connection, mode: .client)
socket.start()
return socket
}
}
}
}
public extension Response {
public var webSocketVersion: String? {
return headers["Sec-Websocket-Version"]
}
public var webSocketKey: String? {
return headers["Sec-Websocket-Key"]
}
public var webSocketAccept: String? {
return headers["Sec-WebSocket-Accept"]
}
public var isWebSocket: Bool {
return connection?.lowercased() == "upgrade" && upgrade?.lowercased() == "websocket"
}
}
| mit | 276ab5f98e5a87e389e4ea4814042a0e | 33.05 | 138 | 0.567233 | 5.08209 | false | false | false | false |
eladb/nodeswift | nodeswift-sample/socket.swift | 1 | 4146 | //
// stream.swift
// nodeswift-sample
//
// Created by Elad Ben-Israel on 7/31/15.
// Copyright © 2015 Citylifeapps Inc. All rights reserved.
//
import Foundation
class Socket: Hashable, Equatable {
let tcp: Handle<uv_tcp_t>
var stream: UnsafeMutablePointer<uv_stream_t> {
return UnsafeMutablePointer<uv_stream_t>(self.tcp.handle)
}
var hashValue: Int {
return self.tcp.hashValue
}
// Events
var data = EventEmitter1<Buffer>()
var end = EventEmitter0()
var closed = EventEmitter0()
var error = ErrorEventEmitter()
var connected = EventEmitter0()
init() {
self.tcp = Handle(closable: true)
self.tcp.callback = self.ondata
uv_tcp_init(uv_default_loop(), self.tcp.handle)
}
deinit {
print("Socket deinit")
}
func connect(port: UInt16, host: String = "localhost", connectionListener: (() -> ())? = nil) {
if let listener = connectionListener {
self.connected.once(listener)
}
let connect = Handle<uv_connect_t>(closable: false)
connect.callback = self.onconnect
let addr = UnsafeMutablePointer<sockaddr_in>.alloc(1);
uv_ip4_addr(host.cStringUsingEncoding(NSUTF8StringEncoding)!, Int32(port), addr)
let result = uv_tcp_connect(connect.handle, self.tcp.handle, UnsafeMutablePointer<sockaddr>(addr), connect_cb)
addr.dealloc(1)
if let err = Error(result: result) {
nextTick { self.error.emit(err) }
return
}
}
func write(string: String, callback: ((Error?) -> ())? = nil) {
let req = Handle<uv_write_t>(closable: false)
req.callback = { args in callback?(args[0] as? Error) }
if let cString = string.cStringUsingEncoding(NSUTF8StringEncoding) {
let buf = UnsafeMutablePointer<uv_buf_t>.alloc(1)
buf.memory = uv_buf_init(UnsafeMutablePointer<Int8>(cString), UInt32(cString.count))
uv_write(req.handle, self.stream, UnsafePointer<uv_buf_t>(buf), 1, write_cb)
}
}
func resume() {
uv_read_start(self.stream, alloc_cb, read_cb)
}
func pause() {
uv_read_stop(self.stream)
}
func close() {
self.tcp.close {
self.closed.emit()
}
}
private func ondata(args: [AnyObject?]) {
let event = args[0] as! String
if event == "data" {
self.data.emit(args[1] as! Buffer)
}
else if event == "end" {
self.end.emit()
self.close()
}
}
private func onconnect(args: [AnyObject?]) {
if let err = args[0] as! Error? {
self.error.emit(err)
}
else {
self.connected.emit()
// start emitting data events
self.resume()
}
}
}
private func connect_cb(handle: UnsafeMutablePointer<uv_connect_t>, result: Int32) {
let err = Error(result: result)
RawHandle.callback(handle, args: [ err ], autoclose: true)
}
private func alloc_cb(handle: UnsafeMutablePointer<uv_handle_t>, suggested_size: Int, buf: UnsafeMutablePointer<uv_buf_t>) {
buf.memory = uv_buf_init(UnsafeMutablePointer<Int8>.alloc(suggested_size), UInt32(suggested_size))
}
private func read_cb(handle: UnsafeMutablePointer<uv_stream_t>, nread: Int, buf: UnsafePointer<uv_buf_t>) {
if Int32(nread) == UV_EOF.rawValue {
// release the buffer and emit "end"
print("Deallocate buf")
buf.memory.base.dealloc(buf.memory.len)
RawHandle.callback(handle, args: [ "end" ], autoclose: false)
return
}
// buf will be deallocated on Buffer deinit
let buffer = Buffer(autoDealloc: buf, nlen: nread)
RawHandle.callback(handle, args: [ "data", buffer ], autoclose: false)
}
private func write_cb(handle: UnsafeMutablePointer<uv_write_t>, status: Int32) {
RawHandle.callback(handle, args: [ Error(result: status) ], autoclose: true)
}
func ==(lhs: Socket, rhs: Socket) -> Bool {
return lhs.tcp == rhs.tcp
}
| apache-2.0 | 6996a29b17c12377f0041406b8bb93d2 | 28.820144 | 124 | 0.597346 | 3.792315 | false | false | false | false |
zhangzichen/Pontus | Pontus/UIKit+Pontus/UINavigationController+Pontus.swift | 1 | 1427 |
import UIKit
public extension UINavigationController {
/**
设置 navigationBar 为纯色
- parameter color: 要设置的纯色
- parameter tintColor: tintColor,默认为白色
- parameter shadowColor: shadowColor,默认为要设置的纯色
*/
func barUseColor(_ color:UIColor, tintColor:UIColor = UIColor.white, shadowColor:UIColor? = nil) -> Self {
// 1×1图片画布
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
// 获取上下文
let ctx = UIGraphicsGetCurrentContext()
// 画方形
ctx?.addRect(CGRect(x: 0, y: 0, width: 1, height: 1))
// 给方形填充颜色
ctx?.setFillColor(color.cgColor)
// 绘制方形
ctx?.fillPath()
// 将当前上线文以image形式输出
let image = UIGraphicsGetImageFromCurrentImageContext()
// 停止绘制图片
UIGraphicsEndImageContext()
navigationBar.setBackgroundImage(image, for: UIBarMetrics.default)
navigationBar.tintColor = tintColor
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : tintColor]
if let shadowColor = shadowColor {
navigationBar.shadowImage = UIImage.imageWithColor(shadowColor)
} else {
navigationBar.shadowImage = image
}
return self
}
}
| mit | 6709e013ba4e90bd25a9149acc11ae4c | 29.761905 | 110 | 0.615325 | 4.969231 | false | false | false | false |
matthew-healy/TableControlling | TableControlling/Model/Table.swift | 1 | 2615 | import Foundation
/**
A view model which represents the contents of a `UITableView`.
It has an optional `Header` and `Footer`, and a non-optional
array of `Section`s (where a `Section` is a `typealias` for
`TableSection<SectionHeader, Cell, SectionFooter>`. The `Header`,
`Footer` and `Section` types are `Equatable` in order for us to equate
entire `Table`s.
*/
struct Table<
Header: Equatable,
SectionHeader: Equatable, Cell: Equatable, SectionFooter:Equatable,
Footer: Equatable
>: Equatable, TableModelling {
typealias Section = TableSection<SectionHeader, Cell, SectionFooter>
let header: Header?
let sections: [Section]
let footer: Footer?
/**
Creates a `Table` with given parameters.
- parameter header: The view model for the table's header. The default argument is `nil`.
- parameter sections: An array of view models for the table's sections. The default argument is an empty array.
- parameter footer: The view model for the table's footer. The default argument is `nil`.
*/
init(header: Header? = nil, sections: [Section] = [], footer: Footer? = nil) {
self.header = header
self.sections = sections
self.footer = footer
}
static func ==<
Header: Equatable,
SectionHeader: Equatable, Cell: Equatable, SectionFooter: Equatable,
Footer: Equatable
>(
lhs: Table<Header, SectionHeader, Cell, SectionFooter, Footer>,
rhs: Table<Header, SectionHeader, Cell, SectionFooter, Footer>
) -> Bool {
return lhs.header == rhs.header
&& lhs.sections == rhs.sections
&& lhs.footer == rhs.footer
}
/**
The number of sections in the `Table`.
*/
var numberOfSections: Int {
return sections.count
}
/**
The number of `Cell`s in the given section of the `Table`.
- parameter section: The `Int` value of the requested section.
- returns: The `numberOfItems` in the section, if it exists, or `0` otherwise.
*/
func numberOfItems(inSection section: Int) -> Int {
return sections[safe: section]?.numberOfItems ?? 0
}
/**
Fetches the item at the given index path of the `Table`.
- parameter indexPath: The `IndexPath` of the requested cell.
- returns: The cell's view model, if it exists, or `nil` otherwise.
*/
func item(at indexPath: IndexPath) -> Cell? {
let (section, row) = (indexPath.section, indexPath.row)
return sections[safe: section]?.item(atRow: row)
}
}
| mit | 1dbbeff8382c01d1b805523cc436a324 | 32.525641 | 116 | 0.636329 | 4.439728 | false | false | false | false |
nathawes/swift | test/Serialization/Recovery/typedefs-in-enums.swift | 22 | 4717 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-sil -o - -emit-module-path %t/Lib.swiftmodule -module-name Lib -I %S/Inputs/custom-modules -disable-objc-attr-requires-foundation-module %s > /dev/null
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules | %FileCheck %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules -Xcc -DBAD | %FileCheck -check-prefix CHECK-RECOVERY %s
// RUN: %target-swift-frontend -typecheck -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST %s -verify
#if TEST
import Typedefs
import Lib
func use(_: OkayEnum) {}
// FIXME: Better to import the enum and make it unavailable.
func use(_: BadEnum) {} // expected-error {{cannot find type 'BadEnum' in scope}}
func test() {
_ = producesOkayEnum()
_ = producesBadEnum() // expected-error {{cannot find 'producesBadEnum' in scope}}
// Force a lookup of the ==
_ = Optional(OkayEnum.noPayload).map { $0 == .noPayload }
}
#else // TEST
import Typedefs
public enum BadEnum {
case noPayload
case perfectlyOkayPayload(Int)
case problematic(Any, WrappedInt)
case alsoOkay(Any, Any, Any)
public static func ==(a: BadEnum, b: BadEnum) -> Bool {
return false
}
}
// CHECK-LABEL: enum BadEnum {
// CHECK-RECOVERY-NOT: enum BadEnum
public enum GenericBadEnum<T: HasAssoc> where T.Assoc == WrappedInt {
case noPayload
case perfectlyOkayPayload(Int)
public static func ==(a: GenericBadEnum<T>, b: GenericBadEnum<T>) -> Bool {
return false
}
}
// CHECK-LABEL: enum GenericBadEnum<T> where T : HasAssoc, T.Assoc == WrappedInt {
// CHECK-RECOVERY-NOT: enum GenericBadEnum
public enum OkayEnum {
case noPayload
case plainOldAlias(Any, UnwrappedInt)
case other(Int)
public static func ==(a: OkayEnum, b: OkayEnum) -> Bool {
return false
}
}
// CHECK-LABEL: enum OkayEnum {
// CHECK-NEXT: case noPayload
// CHECK-NEXT: case plainOldAlias(Any, UnwrappedInt)
// CHECK-NEXT: case other(Int)
// CHECK-NEXT: static func == (a: OkayEnum, b: OkayEnum) -> Bool
// CHECK-NEXT: }
// CHECK-RECOVERY-LABEL: enum OkayEnum {
// CHECK-RECOVERY-NEXT: case noPayload
// CHECK-RECOVERY-NEXT: case plainOldAlias(Any, Int32)
// CHECK-RECOVERY-NEXT: case other(Int)
// CHECK-RECOVERY-NEXT: static func == (a: OkayEnum, b: OkayEnum) -> Bool
// CHECK-RECOVERY-NEXT: }
public enum OkayEnumWithSelfRefs {
public struct Nested {}
indirect case selfRef(OkayEnumWithSelfRefs)
case nested(Nested)
}
// CHECK-LABEL: enum OkayEnumWithSelfRefs {
// CHECK-NEXT: struct Nested {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: indirect case selfRef(OkayEnumWithSelfRefs)
// CHECK-NEXT: case nested(OkayEnumWithSelfRefs.Nested)
// CHECK-NEXT: }
// CHECK-RECOVERY-LABEL: enum OkayEnumWithSelfRefs {
// CHECK-RECOVERY-NEXT: struct Nested {
// CHECK-RECOVERY-NEXT: init()
// CHECK-RECOVERY-NEXT: }
// CHECK-RECOVERY-NEXT: indirect case selfRef(OkayEnumWithSelfRefs)
// CHECK-RECOVERY-NEXT: case nested(OkayEnumWithSelfRefs.Nested)
// CHECK-RECOVERY-NEXT: }
public protocol HasAssoc {
associatedtype Assoc
}
public func producesBadEnum() -> BadEnum { return .noPayload }
// CHECK-LABEL: func producesBadEnum() -> BadEnum
// CHECK-RECOVERY-NOT: func producesBadEnum() -> BadEnum
public func producesGenericBadEnum<T>() -> GenericBadEnum<T> { return .noPayload }
// CHECK-LABEL: func producesGenericBadEnum<T>() -> GenericBadEnum<T>
// CHECK-RECOVERY-NOT: func producesGenericBadEnum
public func producesOkayEnum() -> OkayEnum { return .noPayload }
// CHECK-LABEL: func producesOkayEnum() -> OkayEnum
// CHECK-RECOVERY-LABEL: func producesOkayEnum() -> OkayEnum
extension Int /* or any imported type, really */ {
public enum OkayEnumWithSelfRefs {
public struct Nested {}
indirect case selfRef(OkayEnumWithSelfRefs)
case nested(Nested)
}
}
// CHECK-LABEL: extension Int {
// CHECK-NEXT: enum OkayEnumWithSelfRefs {
// CHECK-NEXT: struct Nested {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: indirect case selfRef(Int.OkayEnumWithSelfRefs)
// CHECK-NEXT: case nested(Int.OkayEnumWithSelfRefs.Nested)
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-RECOVERY-LABEL: extension Int {
// CHECK-RECOVERY-NEXT: enum OkayEnumWithSelfRefs {
// CHECK-RECOVERY-NEXT: struct Nested {
// CHECK-RECOVERY-NEXT: init()
// CHECK-RECOVERY-NEXT: }
// CHECK-RECOVERY-NEXT: indirect case selfRef(Int.OkayEnumWithSelfRefs)
// CHECK-RECOVERY-NEXT: case nested(Int.OkayEnumWithSelfRefs.Nested)
// CHECK-RECOVERY-NEXT: }
// CHECK-RECOVERY-NEXT: }
#endif // TEST
| apache-2.0 | 3f66aeda4c5ee178716c0bc5a8d28a9b | 32.692857 | 188 | 0.701717 | 3.328864 | false | false | false | false |
sschiau/swift | test/Parse/confusables.swift | 1 | 1524 | // RUN: %target-typecheck-verify-swift
// expected-error @+4 {{type annotation missing in pattern}}
// expected-error @+3 {{use of unresolved operator '⁚'}}
// expected-error @+2 {{operator with postfix spacing cannot start a subexpression}}
// expected-error @+1 {{consecutive statements on a line must be separated by ';'}}
let number⁚ Int // expected-note {{operator '⁚' contains possibly confused characters; did you mean to use ':'?}} {{11-14=:}}
// expected-warning @+3 2 {{integer literal is unused}}
// expected-error @+2 {{invalid character in source file}}
// expected-error @+1 {{consecutive statements on a line must be separated by ';'}}
5 ‒ 5 // expected-note {{unicode character '‒' looks similar to '-'; did you mean to use '-'?}} {{3-6=-}}
// expected-error @+2 {{use of unresolved identifier 'ꝸꝸꝸ'}}
// expected-error @+1 {{expected ',' separator}}
if (true ꝸꝸꝸ false) {} // expected-note {{identifier 'ꝸꝸꝸ' contains possibly confused characters; did you mean to use '&&&'?}} {{10-19=&&&}}
// expected-error @+3 {{invalid character in source file}}
// expected-error @+2 {{expected ',' separator}}
// expected-error @+1 {{type '(Int, Int)' cannot conform to 'BinaryInteger'; only struct/enum/class types can conform to protocols}}
if (5 ‒ 5) == 0 {} // expected-note {{unicode character '‒' looks similar to '-'; did you mean to use '-'?}} {{7-10=-}}
// expected-note @-1 {{required by referencing operator function '==' on 'BinaryInteger' where 'Self' = '(Int, Int)'}}
| apache-2.0 | 4ea8ddf77596963786fd9b08c824f4f4 | 66.818182 | 140 | 0.670241 | 3.63017 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.