repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
talk2junior/iOSND-Beginning-iOS-Swift-3.0 | refs/heads/master | Playground Collection/Part 1 - Pirate Fleet 1/Writing Structs with Properties/Writing Structs with Properties Exercises.playground/Contents.swift | mit | 1 | //: ## Writing Structs with Properties Exercises
//: In these exercises, you work with structs and their properties.
//### Exercise 1
//Create a struct called Author that contains the following properties:
struct Author {
let firstName: String
let lastName: String
var living: Bool
}
//### Exercise 2
//Create a struct called Book that contains the following properties:
struct Book {
let title: String
let author: Author
let pages: Int
var numberOfStars: Double
var description: String
var genre: String
}
//### Exercise 3
//Create instances of authors and books based on the following statements:
//- Wilson Rawls was born on September 24, 1913 and passed away on December 16, 1984. He wrote the children's book "Where the Red Fern Grows". This book is about a young boy and his hunting dogs. It is 245 pages and has a 4/5 rating by Common Sense Media.
let rawls = Author(firstName: "Wilson", lastName: "Rawls", living: false)
let whereTheRedFernGrows = Book(title: "Where the Red Fern Grows", author: rawls, pages: 245, numberOfStars: 4, description: "This book is about a young boy and his hunting does.", genre: "Children's Book")
whereTheRedFernGrows.title
whereTheRedFernGrows.author
whereTheRedFernGrows.pages
whereTheRedFernGrows.numberOfStars
whereTheRedFernGrows.description
whereTheRedFernGrows.genre
//- John Ronald Reuel (J. R. R.) Tolkien was born on January 3, 1892 and passed away on September 2, 1973. He wrote the fantasy book "The Hobbit". "The Hobbit" follows the treasure-seeking quest of hobbit Bilbo Baggins and it is about 300 pages long. It has a 4.5/5 rating by Barnes & Noble.
let tolkien = Author(firstName: "J.R.R.", lastName: "Tolkien", living: false)
let theHobbit = Book(title: "The Hobbit", author: tolkien, pages: 300, numberOfStars: 4.5, description: "\"The Hobbit\" follows the treasure-seeking quest of hobbit Bilbo Baggin.", genre: "Fantasy Book")
theHobbit.title
theHobbit.author
theHobbit.description
theHobbit.genre
//- Mary Shelley was born on August 30, 1797 and passed away on February 1, 1851. She wrote the Gothic novel "Frankenstein". "Frankenstein" is about a young science student named Victor Frankenstein who creates a sentient creature in an unorthodox scientific experiment. It is 280 pages long and has a 4.7/5 rating from Google user reviews.
let shelley = Author(firstName: "Mary", lastName: "Shelley", living: false)
let frankenstein = Book(title: "Frankenstein", author: shelley, pages: 280, numberOfStars: 4.7, description: "\"Frankenstein\" is about a young science student named Victor Frankenstein who creates a sentient creature in an unorthodox scientific experiment.", genre: "Gothic")
frankenstein.author
frankenstein.genre
frankenstein.description
frankenstein.pages
| 7e3a557591692e19ed58426991d5e5eb | 42.609375 | 340 | 0.761734 | false | false | false | false |
wyp767363905/GiftSay | refs/heads/master | GiftSay/GiftSay/classes/giftSay/homePage/controller/GiftSayViewController.swift | mit | 1 | //
// GiftSayViewController.swift
// GiftSay
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
import XWSwiftRefresh
class GiftSayViewController: KTCHomeViewController {
private var recommendView: GSRecommendView?
private var otherView: GSOtherView?
private var candidatesArray: Array<GSSmallNavBarChannelsModel>?
private var nextBtn: UIButton?
var scrollView: UIScrollView?
private lazy var otherArray = NSMutableArray()
var num: NSNumber = 102
var smallScrollView: UIScrollView?
var giftType: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
createMyNav()
downloaderSmallNavBarData()
}
//在这是下载出来的是除了精选之外的视图情况?
func downloaderOtherData(){
for i in 0..<otherArray.count {
let urlString = String(format: kGiftSaySelectUrl, "\(otherArray[i])")
let downloader = WYPDownloader()
downloader.type = 500+i
downloader.delegate = self
downloader.downloaderWithUrlString(urlString)
}
}
//创建首页整页的滚动视图
func createHomePageView(){
automaticallyAdjustsScrollViewInsets = false
scrollView = UIScrollView()
scrollView?.pagingEnabled = true
scrollView?.showsHorizontalScrollIndicator = false
scrollView?.delegate = self
view.addSubview(scrollView!)
scrollView?.snp_makeConstraints(closure: {
[weak self]
(make) in
make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(94, 0, 49, 0))
})
let containerView = UIView()
scrollView?.addSubview(containerView)
containerView.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.scrollView!)
make.height.equalTo(self!.scrollView!)
}
//精选视图(特殊)
recommendView = GSRecommendView()
containerView.addSubview(recommendView!)
recommendView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo(containerView)
})
//其他视图是一样的
var lastView: UIView? = nil
if otherArray.count > 0 {
for i in 0..<otherArray.count {
otherView = GSOtherView()
containerView.addSubview(otherView!)
otherView?.snp_makeConstraints(closure: {
[weak self]
(make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
if i == 0 {
make.left.equalTo((self!.recommendView?.snp_right)!)
}else{
make.left.equalTo((lastView?.snp_right)!)
}
})
otherView?.tag = 800+i
lastView = otherView
}
containerView.snp_makeConstraints(closure: { (make) in
make.right.equalTo(lastView!)
})
}
addFoot()
addHead()
}
//上拉
func addFoot(){
recommendView?.tbView?.footerView = XWRefreshAutoNormalFooter(target: self, action: #selector(loadNextPage))
// for i in 0..<otherArray.count {
// otherView?.tbView?.footerView = XWRefreshAutoNormalFooter(target: self, action: #selector(nextPage))
//
// }
}
func nextPage(){
giftType = 1
otherView?.number = giftType
kGiftSaySelectUrl = (otherView?.otherModel?.data?.paging?.next_url)!
}
func loadNextPage(){
giftType = 1
recommendView?.number = giftType
kGiftSaySelectUrl = (recommendView?.selectModel?.data?.paging?.next_url)!
downloaderSelectData()
}
//下拉
func addHead(){
recommendView?.tbView?.headerView = XWRefreshNormalHeader(target: self, action: #selector(loadFirstPage))
//otherView?.tbView?.headerView = XWRefreshNormalHeader(target: self, action: #selector(firstPage))
}
func firstPage(){
giftType = 0
otherView?.number = giftType
kGiftSaySelectUrl = "http://api.liwushuo.com/v2/channels/%@/items_v2?ad=2&gender=1&generation=3&limit=20&offset=0"
}
func loadFirstPage(){
giftType = 0
recommendView?.number = giftType
kGiftSaySelectUrl = "http://api.liwushuo.com/v2/channels/%@/items_v2?ad=2&gender=1&generation=3&limit=20&offset=0"
downloaderAdData()
downloaderSecondaryBannersData()
downloaderSelectData()
downloaderOtherData()
downloaderSelectData()
}
//精选
func downloaderSelectData() {
var urlString = ""
if giftType == 0 {
urlString = String(format: kGiftSaySelectUrl, num)
}else if giftType == 1 {
urlString = kGiftSaySelectUrl
}
let downloader = WYPDownloader()
downloader.type = 400
downloader.delegate = self
downloader.downloaderWithUrlString(urlString)
}
//次要的横幅
func downloaderSecondaryBannersData() {
let urlString = kGiftSayBannersUrl
let downloader = WYPDownloader()
downloader.type = 300
downloader.delegate = self
downloader.downloaderWithUrlString(urlString)
}
//滚动视图数据下载
func downloaderAdData() {
let urlString = kGiftSayAdUrl
let downloader = WYPDownloader()
downloader.type = 200
downloader.delegate = self
downloader.downloaderWithUrlString(urlString)
}
//小导航栏数据下载
func downloaderSmallNavBarData() {
let urlString = kGiftSaySmallNavBarUrl
let downloader = WYPDownloader()
downloader.type = 100
downloader.delegate = self
downloader.downloaderWithUrlString(urlString)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.barTintColor = UIColor.redColor()
}
//导航
func createMyNav(){
addNavTitle("礼物说")
addNavBtn("sign_in", targer: self, action: #selector(signInAction), isLeft: true)
addNavBtn("search", targer: self, action: #selector(searchAction), isLeft: false)
}
func signInAction(){
}
func searchAction(){
}
//创建小导航栏
func createSmallNavBarBtn(){
automaticallyAdjustsScrollViewInsets = false
smallScrollView = UIScrollView()
smallScrollView?.showsHorizontalScrollIndicator = false
view.addSubview(smallScrollView!)
//滚动视图约束
smallScrollView?.snp_makeConstraints {
[weak self]
(make) in
make.top.equalTo(self!.view).offset(64)
make.left.equalTo(self!.view)
make.right.equalTo(self!.view).offset(-30)
make.height.equalTo(30)
}
let smallContainerView = UIView()
smallContainerView.tag = 10
smallScrollView?.addSubview(smallContainerView)
//容器视图约束
smallContainerView.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.smallScrollView!)
make.height.equalTo(self!.smallScrollView!)
}
createBtnAndAlterView(smallContainerView)
}
//创建小导航栏上面的按钮并修改容器视图
func createBtnAndAlterView(smallContainerView: UIView) {
var lastBtn: UIButton? = nil
let cnt = candidatesArray?.count
if cnt > 0 {
for i in 0..<cnt! {
let model = candidatesArray![i]
let dict = [NSFontAttributeName: UIFont.systemFontOfSize(13)]
let tmpBtn = UIButton.createBtn(model.name!, bgImageName: nil, selectBgImageName: nil, target: self, action: #selector(clickBtn(_:)))
tmpBtn.tag = 1000+i
tmpBtn.titleLabel?.font = UIFont.systemFontOfSize(13)
let nameStr = NSString(string: model.name!)
let tmpBtnRect = nameStr.boundingRectWithSize(CGSizeMake(CGFloat.max, tmpBtn.frame.size.height), options: .TruncatesLastVisibleLine, attributes: dict, context: nil)
smallContainerView.addSubview(tmpBtn)
tmpBtn.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(smallContainerView)
make.width.equalTo(tmpBtnRect.size.width)
if i == 0 {
make.left.equalTo(smallContainerView).offset(10)
}else{
make.left.equalTo((lastBtn?.snp_right)!).offset(10)
}
})
lastBtn = tmpBtn
if i == 0 {
tmpBtn.selected = true
tmpBtn.setTitleColor(UIColor.redColor(), forState: .Normal)
nextBtn = tmpBtn
}
}
//修改容器视图约束
smallContainerView.snp_makeConstraints(closure: {
(make) in
make.right.equalTo((lastBtn?.snp_right)!).offset(10)
})
}
}
//小导航栏按钮的点击事件
func clickBtn(tmpBtn: UIButton){
//点击选中情况
if nextBtn != nil {
nextBtn?.selected = false
nextBtn?.setTitleColor(UIColor.blackColor(), forState: .Normal)
tmpBtn.selected = true
tmpBtn.setTitleColor(UIColor.redColor(), forState: .Normal)
}
UIView.beginAnimations("donghua", context: nil)
UIView.setAnimationDuration(0.5)
UIView.setAnimationRepeatCount(1)
UIView.setAnimationDelegate(self)
var offsetX = tmpBtn.center.x-(smallScrollView?.center.x)!
if offsetX < 0 {
offsetX = 0
}
if offsetX > ((smallScrollView?.contentSize.width)!-(smallScrollView?.bounds.size.width)!) {
offsetX = (smallScrollView?.contentSize.width)!-(smallScrollView?.bounds.size.width)!
}
smallScrollView?.contentOffset = CGPointMake(offsetX, 0)
UIView.commitAnimations()
nextBtn = tmpBtn
}
func gotoADDetail(targetId: String?, type: String, targetUrl: String?) {
let adDetailCtrl = ADDetailViewController()
adDetailCtrl.targetId = targetId
adDetailCtrl.type = type
adDetailCtrl.targetUrl = targetUrl
navigationController?.pushViewController(adDetailCtrl, animated: true)
}
func showRecommendData(model: GSRecommendModel){
recommendView?.model = model
recommendView?.clickClosure = {
[weak self]
(targetId: String?, type: String, targetUrl: String?) in
self!.gotoADDetail(targetId, type: type, targetUrl: targetUrl)
}
}
func showSelectData(model: GSSelectModel,tag: Int){
if tag == 400 {
recommendView?.selectModel = model
recommendView?.clickClosure = {
[weak self]
(targetId: String?, type: String, targetUrl: String?) in
self!.gotoADDetail(targetId, type: type, targetUrl: targetUrl)
}
}else{
let subView = self.scrollView?.viewWithTag(300+tag)
if ((subView?.isKindOfClass(GSOtherView.self)) == true) {
let otherView = subView as! GSOtherView
otherView.otherModel = model
otherView.clickClosure = {
[weak self]
(targetId: String?, type: String, targetUrl: String?) in
self!.gotoADDetail(targetId, type: type, targetUrl: targetUrl)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
//MARK: WYPDownloader代理
extension GiftSayViewController : WYPDownloaderDelegate {
func downloader(downloader: WYPDownloader, didFailWithError error: NSError) {
print(error)
}
func downloader(downloader: WYPDownloader, didFinishWithData data: NSData?) {
if let jsonData = data {
if downloader.type == 100 {
let model = GSSmallNavBarModel.parseModel(jsonData)
candidatesArray = model.data?.channels
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.createSmallNavBarBtn()
if model.data?.candidates?.count > 0 {
for i in 0..<(model.data?.candidates?.count)! {
let id = model.data?.candidates![i].id
self!.otherArray.addObject(id!)
}
self!.createHomePageView()
self!.downloaderAdData()
self!.downloaderSecondaryBannersData()
self!.downloaderSelectData()
self!.downloaderOtherData()
}
})
}else if downloader.type == 200 {
let model = GSRecommendModel.parseModel(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.showRecommendData(model)
})
}else if downloader.type == 300 {
let model = GSSecondaryBannersModel.parseModel(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.recommendView?.secondaryBannersModel = model
})
}else if downloader.type == 400 {
/*
let str = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
print(str!)
*/
let model = GSSelectModel.parseModel(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.showSelectData(model,tag: 400)
self!.recommendView?.tbView?.footerView?.endRefreshing()
self!.recommendView?.tbView?.headerView?.endRefreshing()
})
}else{
for i in 0..<otherArray.count {
if downloader.type == 500+i {
let model = GSSelectModel.parseModel(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self!.showSelectData(model,tag: 500+i)
})
}
}
}
}
}
}
extension GiftSayViewController : UIScrollViewDelegate {
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x/scrollView.bounds.size.width)
let subView = smallScrollView?.viewWithTag(1000+index)
if subView?.isKindOfClass(UIButton.self) == true {
let tmpBtn = subView as! UIButton
if nextBtn != nil {
nextBtn?.selected = false
nextBtn?.setTitleColor(UIColor.blackColor(), forState: .Normal)
tmpBtn.selected = true
tmpBtn.setTitleColor(UIColor.redColor(), forState: .Normal)
}
UIView.beginAnimations("donghua", context: nil)
UIView.setAnimationDuration(0.5)
UIView.setAnimationRepeatCount(1)
UIView.setAnimationDelegate(self)
var offsetX = tmpBtn.center.x-(smallScrollView?.center.x)!
if offsetX < 0 {
offsetX = 0
}
if offsetX > ((smallScrollView?.contentSize.width)!-(smallScrollView?.bounds.size.width)!) {
offsetX = (smallScrollView?.contentSize.width)!-(smallScrollView?.bounds.size.width)!
}
smallScrollView?.contentOffset = CGPointMake(offsetX, 0)
UIView.commitAnimations()
nextBtn = tmpBtn
}
}
}
| 273fbfb1839ffb49d5b0d33a51182cad | 29.639866 | 180 | 0.520993 | false | false | false | false |
amcnary/cs147_instagator | refs/heads/master | instagator-prototype/instagator-prototype/PollResultsViewController.swift | apache-2.0 | 1 | //
// PollResultsViewController.swift
// instagator-prototype
//
// Created by Amanda McNary on 11/29/15.
// Copyright © 2015 ThePenguins. All rights reserved.
//
import Foundation
import UIKit
protocol PollResultsViewControllerDelegate {
func pollResultsViewController(pollResultsViewController: PollResultsViewController, selectAndSaveButtonTappedForEvent event: Event)
}
class PollResultsViewController: UIViewController, UITableViewDataSource {
// MARK: Interface Outlets
@IBAction func pollResultInfoButtonTapped(sender: AnyObject) {
self.presentConfirmationMessage("Satisfaction rates are calculated by weighting the preferences of the different options from each poll response. First place votes are given the most weight, followed by second place, and so on.")
}
@IBOutlet weak var pollResultsTitleLabel: UILabel!
@IBOutlet weak var pollResponseProgressLabel: UILabel!
@IBOutlet weak var pollSendReminderButton: UIButton!
@IBOutlet weak var pollTopActivityNameLabel: UILabel!
@IBOutlet weak var pollTopActivityDatesLabel: UILabel!
@IBOutlet weak var pollTopActivityProjectedCostLabel: UILabel!
@IBOutlet weak var pollTopActivityDescriptionLabel: UILabel!
@IBOutlet weak var pollDetailedResultsTableView: UITableView!
@IBOutlet weak var pollSelectAndCloseButton: UIButton!
@IBAction func pollSelectAndCloseButtonTapped(sender: AnyObject) {
// send winning event back to delegate
// dismiss this page forever
// change the activity from the poll to the winning event
if let unwrappedPoll = self.poll {
self.delegate?.pollResultsViewController(self, selectAndSaveButtonTappedForEvent: unwrappedPoll.Options[0])
}
}
@IBAction func deletePollButtonTapped(sender: AnyObject) {
}
@IBAction func sendVoteReminderTapped(sender: AnyObject) {
self.presentConfirmationMessage("Reminder sent!")
}
// MARK: other properties
var poll: Poll?
var delegate: PollResultsViewControllerDelegate?
// MARK: lifecycle
override func viewDidLoad() {
if let unwrappedPoll = poll {
self.pollResultsTitleLabel.text = unwrappedPoll.Name
self.pollResponseProgressLabel.text = "\(unwrappedPoll.NumPeopleResponded)/\(unwrappedPoll.People.count) Responded"
if unwrappedPoll.NumPeopleResponded != 0 {
let winningOption = unwrappedPoll.Options[0]
self.pollTopActivityNameLabel.text = winningOption.Name
self.pollTopActivityDescriptionLabel.text = winningOption.Description
let startTime = dateTimeFormatter.stringFromDate(winningOption.StartDate)
let endTime = dateTimeFormatter.stringFromDate(winningOption.EndDate)
self.pollTopActivityDatesLabel.text = "\(startTime) to \(endTime)"
if let projectedCost = winningOption.Cost {
self.pollTopActivityProjectedCostLabel.text = "$\(projectedCost)0"
}
} else if unwrappedPoll.NumPeopleResponded == unwrappedPoll.People.count {
self.pollSendReminderButton.hidden = true
} else {
self.pollTopActivityNameLabel.text = "No winner yet. Lowest-cost approach?"
self.pollTopActivityDatesLabel.hidden = true
self.pollTopActivityProjectedCostLabel.hidden = true
self.pollTopActivityDescriptionLabel.hidden = true
self.pollSelectAndCloseButton.hidden = true
}
}
super.viewDidLoad()
}
// MARK: UITableViewDataSource protocol methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// TODO: dequeue the cell we want, fill its subviews, and return it
if let unwrappedPoll = poll, cell = tableView.dequeueReusableCellWithIdentifier(PollActivityResultTableViewCell.reuseIdentifier, forIndexPath: indexPath) as? PollActivityResultTableViewCell {
let currentOption = unwrappedPoll.Options[indexPath.row]
cell.activityNameLabel.text = currentOption.Name
cell.activitySatisfactionLabel.text = "Satisfaction: \(unwrappedPoll.Results[indexPath.row] * 100)%"
return cell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return poll?.Options.count ?? 0
}
} | eb0c8b93389f588c4627f02537a03309 | 44.68 | 237 | 0.700898 | false | false | false | false |
aikizoku/SKLogDebugger-iOS | refs/heads/master | Example/Pods/SwiftyAttributes/SwiftyAttributes/Sources/common/Attribute.swift | mit | 2 | //
// Attribute.swift
// SwiftyAttributes
//
// Created by Eddie Kaiger on 10/15/16.
// Copyright © 2016 Eddie Kaiger. All rights reserved.
//
#if os(macOS)
import AppKit
public typealias Color = NSColor
public typealias Font = NSFont
public typealias Cursor = NSCursor
public typealias TextAlternatives = NSTextAlternatives
#else
import UIKit
public typealias Color = UIColor
public typealias Font = UIFont
#endif
public typealias UnderlineStyle = NSUnderlineStyle
public typealias StrikethroughStyle = NSUnderlineStyle
public typealias ParagraphStyle = NSParagraphStyle
#if os(watchOS)
#else
public typealias Shadow = NSShadow
public typealias TextAttachment = NSTextAttachment
#endif
/**
Represents attributes that can be applied to NSAttributedStrings.
*/
public enum Attribute {
#if os(watchOS)
#else
/// Attachment attribute that allows items like images to be inserted into text.
case attachment(TextAttachment)
#endif
/// Value indicating the character's offset from the baseline, in points.
case baselineOffset(Double)
/// The background color of the attributed string.
case backgroundColor(Color)
#if os(macOS)
/// The cursor object associated with the attributed string.
case cursor(Cursor)
#endif
/// Value indicating the log of the expansion factor to be applied to glyphs.
case expansion(Double)
/// The font of the attributed string.
case font(Font)
/// Specifies the number of points by which to adjust kern-pair characters. Kerning prevents unwanted space from occurring between specific characters and depends on the font. The value 0 means kerning is disabled (default).
case kern(Double)
/// Ligatures cause specific character combinations to be rendered using a single custom glyph that corresponds to those characters. See `Ligatures` for values.
case ligatures(Ligatures)
/// A URL link to attach to the attributed string.
case link(URL)
#if os(macOS)
/// The index in marked text indicating clause segments.
case markedClauseSegment(Int)
#endif
/// A value indicating the skew to be applied to glyphs.
case obliqueness(Double)
/// An `NSParagraphStyle` to be applied to the attributed string.
case paragraphStyle(ParagraphStyle)
#if os(watchOS)
#else
/// A shadow to be applied to the characters.
case shadow(Shadow)
#endif
#if os(macOS)
/// A state indicating a spelling or grammar error. See `SpellingState` for possible values.
case spellingState(SpellingState)
#endif
/// The color of the stroke (border) around the characters.
case strokeColor(Color)
/// The width/thickness of the stroke (border) around the characters.
case strokeWidth(Double)
/// The color of the strikethrough.
case strikethroughColor(Color)
/// The style of the strikethrough.
case strikethroughStyle(StrikethroughStyle)
#if os(macOS)
/// The superscript attribute.
case superscript(Int)
/// The object representing alternatives for a string that may be presented to the user.
case textAlternatives(TextAlternatives)
#endif
/// The text color.
case textColor(Color)
/// The text effect to apply. See `TextEffect` for possible values.
case textEffect(TextEffect)
#if os(macOS)
/// The text of the tooltip.
case toolTip(String)
#endif
/// The color of the underline.
case underlineColor(Color)
/// The style of the underline.
case underlineStyle(UnderlineStyle)
/// The vertical glyph form (horizontal or vertical text). See `VerticalGlyphForm` for details.
case verticalGlyphForm(VerticalGlyphForm)
/// The writing directions to apply to the attributed string. See `WritingDirection` for values. Only available on iOS 9.0+.
case writingDirections([WritingDirection])
/// A custom attribute with a given attribute name and value.
case custom(String, Any)
init(name: NSAttributedString.Key, foundationValue: Any) {
func validate<Type>(_ val: Any) -> Type {
assert(val is Type, "Attribute with name \(name.rawValue) must have a value of type \(Type.self)")
return val as! Type
}
func validateDouble(_ val: Any) -> Double {
assert(val is NSNumber, "Attribute with name \(name.rawValue) must have a value that is castable to NSNumber")
return (val as! NSNumber).doubleValue
}
var ret: Attribute!
// Bug in Swift prevents us from putting directives inside switch statements (https://bugs.swift.org/browse/SR-2)
#if os(watchOS)
#else
switch name {
case .attachment: ret = .attachment(validate(foundationValue))
case .shadow: ret = .shadow(validate(foundationValue))
default: break
}
#endif
#if os(macOS)
switch name {
case .cursor: ret = .cursor(validate(foundationValue))
case .markedClauseSegment: ret = .markedClauseSegment(validate(foundationValue))
case .spellingState: ret = .spellingState(SpellingState(rawValue: validate(foundationValue))!)
case .superscript: ret = .superscript(validate(foundationValue))
case .textAlternatives: ret = .textAlternatives(validate(foundationValue))
case .toolTip: ret = .toolTip(validate(foundationValue))
default: break
}
#endif
switch name {
case .baselineOffset: ret = .baselineOffset(validateDouble(foundationValue))
case .backgroundColor: ret = .backgroundColor(validate(foundationValue))
case .expansion: ret = .expansion(validateDouble(foundationValue))
case .font: ret = .font(validate(foundationValue))
case .kern: ret = .kern(validateDouble(foundationValue))
case .ligature: ret = .ligatures(Ligatures(rawValue: validate(foundationValue))!)
case .link: ret = .link(validate(foundationValue))
case .obliqueness: ret = .obliqueness(validateDouble(foundationValue))
case .paragraphStyle: ret = .paragraphStyle(validate(foundationValue))
case .strokeColor: ret = .strokeColor(validate(foundationValue))
case .strokeWidth: ret = .strokeWidth(validateDouble(foundationValue))
case .strikethroughColor: ret = .strikethroughColor(validate(foundationValue))
case .strikethroughStyle: ret = .strikethroughStyle(StrikethroughStyle(rawValue: validate(foundationValue)))
case .foregroundColor: ret = .textColor(validate(foundationValue))
case .textEffect: ret = .textEffect(TextEffect(rawValue: validate(foundationValue))!)
case .underlineColor: ret = .underlineColor(validate(foundationValue))
case .underlineStyle: ret = .underlineStyle(UnderlineStyle(rawValue: validate(foundationValue)))
case .verticalGlyphForm: ret = .verticalGlyphForm(VerticalGlyphForm(rawValue: validate(foundationValue))!)
case .writingDirection:
let values: [Int] = validate(foundationValue)
ret = .writingDirections(values.compactMap(WritingDirection.init))
default:
if ret == nil {
ret = .custom(name.rawValue, foundationValue)
}
}
self = ret
}
/// The key name corresponding to the attribute.
public var keyName: NSAttributedString.Key {
var name: NSAttributedString.Key!
// Bug in Swift prevents us from putting directives inside switch statements (https://bugs.swift.org/browse/SR-2)
#if os(watchOS)
#else
switch self {
case .attachment: name = .attachment
case .shadow: name = .shadow
default: break
}
#endif
#if os(macOS)
switch self {
case .cursor: name = .cursor
case .markedClauseSegment: name = .markedClauseSegment
case .spellingState: name = .spellingState
case .superscript: name = .superscript
case .textAlternatives: name = .textAlternatives
case .toolTip: name = .toolTip
default: break
}
#endif
switch self {
case .baselineOffset: name = .baselineOffset
case .backgroundColor: name = .backgroundColor
case .expansion: name = .expansion
case .font: name = .font
case .kern: name = .kern
case .ligatures: name = .ligature
case .link: name = .link
case .obliqueness: name = .obliqueness
case .paragraphStyle: name = .paragraphStyle
case .strokeColor: name = .strokeColor
case .strokeWidth: name = .strokeWidth
case .strikethroughColor: name = .strikethroughColor
case .strikethroughStyle: name = .strikethroughStyle
case .textColor: name = .foregroundColor
case .textEffect: name = .textEffect
case .underlineColor: name = .underlineColor
case .underlineStyle: name = .underlineStyle
case .writingDirections: name = .writingDirection
case .verticalGlyphForm: name = .verticalGlyphForm
case .custom(let attributeName, _) where name == nil:
name = NSAttributedString.Key(rawValue: attributeName)
default: break
}
return name
}
// Convenience getter variable for the associated value of the attribute. See each case to determine the return type.
public var value: Any {
// Bug in Swift prevents us from putting directives inside switch statements (https://bugs.swift.org/browse/SR-2)
#if os(watchOS)
#else
switch self {
case .attachment(let attachment): return attachment
case .shadow(let shadow): return shadow
default: break
}
#endif
#if os(macOS)
switch self {
case .cursor(let cursor): return cursor
case .markedClauseSegment(let segment): return segment
case .spellingState(let state): return state
case .superscript(let superscript): return superscript
case .textAlternatives(let alternatives): return alternatives
case .toolTip(let text): return text
default: break
}
#endif
switch self {
case .baselineOffset(let offset): return offset
case .backgroundColor(let color): return color
case .expansion(let expansion): return expansion
case .font(let font): return font
case .kern(let kern): return kern
case .ligatures(let ligatures): return ligatures
case .link(let link): return link
case .obliqueness(let value): return value
case .paragraphStyle(let style): return style
case .strokeColor(let color): return color
case .strokeWidth(let width): return width
case .strikethroughColor(let color): return color
case .strikethroughStyle(let style): return style
case .textColor(let color): return color
case .textEffect(let effect): return effect
case .underlineColor(let color): return color
case .underlineStyle(let style): return style
case .verticalGlyphForm(let form): return form
case .writingDirections(let directions): return directions
case .custom(_, let value): return value
default:
fatalError("No value found for attribute \(self)")
}
}
/// The value that is passed into the original attribute dictionary of Foundation's API for NSAttributedStrings. Consists of basic types such as Int, Color, Font, etc.
public var foundationValue: Any {
#if os(macOS)
switch self {
case .spellingState(let state): return state.rawValue
default: break
}
#endif
switch self {
case .ligatures(let ligatures): return ligatures.rawValue
case .strikethroughStyle(let style): return style.rawValue
case .textEffect(let effect): return effect.rawValue
case .underlineStyle(let style): return style.rawValue
case .writingDirections(let directions): return directions.map { $0.rawValue }
case .verticalGlyphForm(let form): return form.rawValue
default: return value
}
}
}
extension Attribute: Equatable { }
public func == (lhs: Attribute, rhs: Attribute) -> Bool {
return (lhs.foundationValue as? NSObject) == (rhs.foundationValue as? NSObject)
}
| 55e4e3dd90dee2f0550e8948c66f6ebe | 36.680597 | 228 | 0.661491 | false | false | false | false |
gtrabanco/JSQDataSourcesKit | refs/heads/develop | JSQDataSourcesKit/JSQDataSourcesKitTests/CollectionViewDataSourceTests.swift | mit | 2 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://jessesquires.com/JSQDataSourcesKit
//
//
// GitHub
// https://github.com/jessesquires/JSQDataSourcesKit
//
//
// License
// Copyright (c) 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import UIKit
import Foundation
import XCTest
import JSQDataSourcesKit
// MARK: fakes
private struct FakeCollectionModel: Equatable {
let name = NSProcessInfo.processInfo().globallyUniqueString
}
private func ==(lhs: FakeCollectionModel, rhs: FakeCollectionModel) -> Bool {
return lhs.name == rhs.name
}
private class FakeCollectionCell: UICollectionViewCell { }
private class FakeCollectionSupplementaryView: UICollectionReusableView { }
private class FakeCollectionView: UICollectionView {
var dequeueCellExpectation: XCTestExpectation?
var dequeueSupplementaryViewExpectation: XCTestExpectation?
override func dequeueReusableCellWithReuseIdentifier(identifier: String, forIndexPath indexPath: NSIndexPath!) -> AnyObject {
dequeueCellExpectation?.fulfill()
return super.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath)
}
override func dequeueReusableSupplementaryViewOfKind(elementKind: String, withReuseIdentifier identifier: String, forIndexPath indexPath: NSIndexPath!) -> AnyObject {
dequeueSupplementaryViewExpectation?.fulfill()
return super.dequeueReusableSupplementaryViewOfKind(elementKind, withReuseIdentifier: identifier, forIndexPath: indexPath)
}
}
private let FakeSupplementaryViewKind = "FakeSupplementaryViewKind"
private class FakeFlowLayout: UICollectionViewFlowLayout {
private override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
if elementKind == FakeSupplementaryViewKind {
return UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, withIndexPath: indexPath)
}
return super.layoutAttributesForSupplementaryViewOfKind(elementKind, atIndexPath: indexPath)
}
}
private typealias CellFactory = CollectionViewCellFactory<FakeCollectionCell, FakeCollectionModel>
private typealias SupplementaryViewFactory = CollectionSupplementaryViewFactory<FakeCollectionSupplementaryView, FakeCollectionModel>
private typealias Section = CollectionViewSection<FakeCollectionModel>
private typealias Provider = CollectionViewDataSourceProvider<FakeCollectionModel, Section, CellFactory, SupplementaryViewFactory>
// MARK: test case
class CollectionViewDataSourceTests: XCTestCase {
// MARK: setup
let fakeCellReuseId = "fakeCellId"
let fakeSupplementaryViewReuseId = "fakeSupplementaryId"
private let fakeCollectionView = FakeCollectionView(frame: CGRect(x: 0, y: 0, width: 320, height: 600), collectionViewLayout: FakeFlowLayout())
let dequeueCellExpectationName = "collectionview_dequeue_cell_expectation"
let dequeueSupplementaryViewExpectationName = "collectionview_dequeue_supplementaryview_expectation"
override func setUp() {
super.setUp()
fakeCollectionView.registerClass(FakeCollectionCell.self, forCellWithReuseIdentifier: fakeCellReuseId)
fakeCollectionView.registerClass(FakeCollectionSupplementaryView.self, forSupplementaryViewOfKind: FakeSupplementaryViewKind, withReuseIdentifier: fakeSupplementaryViewReuseId)
}
override func tearDown() {
super.tearDown()
}
// MARK: tests
func test_ThatCollectionViewSectionReturnsExpectedDataFromSubscript() {
// GIVEN: a model and a collection view section
let expectedModel = FakeCollectionModel()
let section = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), expectedModel])
// WHEN: we ask for an item at a specific index
let item = section[3]
// THEN: we receive the expected item
XCTAssertEqual(item, expectedModel, "Model returned from subscript should equal expected model")
}
func test_ThatCollectionViewSectionSetsExpectedDataAtSubscript() {
// GIVEN: a collection view section
var section = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel()])
let count = section.count
// WHEN: we set an item at a specific index
let index = 1
let expectedModel = FakeCollectionModel()
section[index] = expectedModel
// THEN: the item at the specified index is replaced with the new item
XCTAssertEqual(section[index], expectedModel, "Model set at subscript should equal expected model")
XCTAssertEqual(count, section.count, "Section count should remain unchanged")
}
func test_ThatCollectionViewSectionReturnsExpectedCount() {
// GIVEN: items and a collection view section
let items = [FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel()]
let section = CollectionViewSection(dataItems: items)
// WHEN: we ask the section for its count
let count = section.count
// THEN: we receive the expected count
XCTAssertEqual(count, items.count, "Count should equal expected count")
XCTAssertEqual(count, section.dataItems.count, "Count should equal expected count")
}
func test_ThatCollectionViewDataSourceProviderReturnsExpectedDataFromSubscript() {
// GIVEN: some collection view sections
let section0 = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel()])
let section1 = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel()])
let section2 = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel()])
let sections = [section0, section1, section2]
// GIVEN: a cell factory
let cellFactory = CollectionViewCellFactory(reuseIdentifier: "reuseId", cellConfigurator: { (cell: UICollectionViewCell, model: FakeCollectionModel, view: UICollectionView, index: NSIndexPath) -> UICollectionViewCell in
return cell
})
// GIVEN: a supplementary view factory
let viewFactory = CollectionSupplementaryViewFactory(reuseIdentifier: "reuseId") { (view: UICollectionReusableView, model: FakeCollectionModel, kind: String, collectionView: UICollectionView, index: NSIndexPath) -> UICollectionReusableView in
return view
}
// GIVEN: a data source provider
let dataSourceProvider = CollectionViewDataSourceProvider(sections: sections, cellFactory: cellFactory, supplementaryViewFactory: viewFactory)
// WHEN: we ask for a section at a specific index
let section = dataSourceProvider[1]
// THEN: we receive the expected section
XCTAssertEqual(section.dataItems, section1.dataItems, "Section returned from subscript should equal expected section")
}
func test_ThatCollectionViewDataSourceProviderSetsExpectedDataAtSubscript() {
// GIVEN: some collection view sections
let section0 = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel()])
let section1 = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel()])
let section2 = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel()])
let allSections = [section0, section1, section2]
// GIVEN: a cell factory
let factory = CollectionViewCellFactory(reuseIdentifier: self.fakeCellReuseId) { (cell: FakeCollectionCell, model: FakeCollectionModel, view: UICollectionView, index: NSIndexPath) -> FakeCollectionCell in
return cell
}
// GIVEN: a data source provider
let dataSourceProvider: Provider = CollectionViewDataSourceProvider(sections: allSections, cellFactory: factory)
let count = dataSourceProvider.sections.count
// WHEN: we set a section at a specific index
let index = 0
let expectedSection = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel()])
dataSourceProvider[index] = expectedSection
// THEN: the section at the specified index is replaced with the new section
XCTAssertEqual(dataSourceProvider[index].dataItems, expectedSection.dataItems, "Section set at subscript should equal expected section")
XCTAssertEqual(count, dataSourceProvider.sections.count, "Number of sections should remain unchanged")
}
func test_ThatCollectionViewDataSourceReturnsExpectedData_ForSingleSection() {
// GIVEN: a single CollectionViewSection with data items
let expectedModel = FakeCollectionModel()
let expectedIndexPath = NSIndexPath(forRow: 3, inSection: 0)
let section0 = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), expectedModel, FakeCollectionModel()])
let allSections = [section0]
let cellFactoryExpectation = self.expectationWithDescription("\(__FUNCTION__)")
self.fakeCollectionView.dequeueCellExpectation = self.expectationWithDescription(self.dequeueCellExpectationName + "\(__FUNCTION__)")
// GIVEN: a cell factory
let factory = CollectionViewCellFactory(reuseIdentifier: self.fakeCellReuseId) { (cell: FakeCollectionCell, model: FakeCollectionModel, view: UICollectionView, indexPath: NSIndexPath) -> FakeCollectionCell in
XCTAssertEqual(cell.reuseIdentifier, self.fakeCellReuseId, "Dequeued cell should have expected identifier")
XCTAssertEqual(view, self.fakeCollectionView, "CollectionView should equal the collectionView for the data source")
XCTAssertEqual(model, expectedModel, "Model object should equal expected value")
XCTAssertEqual(indexPath, expectedIndexPath, "IndexPath should equal expected value")
cellFactoryExpectation.fulfill()
return cell
}
// GIVEN: a data source provider
typealias CellFactory = CollectionViewCellFactory<FakeCollectionCell, FakeCollectionModel>
typealias SupplementaryViewFactory = CollectionSupplementaryViewFactory<FakeCollectionSupplementaryView, FakeCollectionModel>
typealias Section = CollectionViewSection<FakeCollectionModel>
typealias Provider = CollectionViewDataSourceProvider<FakeCollectionModel, Section, CellFactory, SupplementaryViewFactory>
let dataSourceProvider: Provider = CollectionViewDataSourceProvider(sections: allSections, cellFactory: factory, collectionView: self.fakeCollectionView)
let dataSource = dataSourceProvider.dataSource
// WHEN: we call the collection view data source methods
let numSections = dataSource.numberOfSectionsInCollectionView?(self.fakeCollectionView)
let numRows = dataSource.collectionView(self.fakeCollectionView, numberOfItemsInSection: 0)
let cell = dataSource.collectionView(self.fakeCollectionView, cellForItemAtIndexPath: expectedIndexPath)
// THEN: we receive the expected return values
XCTAssertNotNil(numSections, "Number of sections should not be nil")
XCTAssertEqual(numSections!, dataSourceProvider.sections.count, "Data source should return expected number of sections")
XCTAssertEqual(numRows, section0.count, "Data source should return expected number of rows for section 0")
XCTAssertEqual(cell.reuseIdentifier, self.fakeCellReuseId, "Data source should return cells with the expected identifier")
// THEN: the collectionView calls `dequeueReusableCellWithReuseIdentifier`
// THEN: the cell factory calls its `ConfigurationHandler`
self.waitForExpectationsWithTimeout(1, handler: { (error) -> Void in
XCTAssertNil(error, "Expectation should not error")
})
}
func test_ThatCollectionViewDataSourceReturnsExpectedData_ForMultipleSections() {
// GIVEN: some collection view sections
let section0 = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel()])
let section1 = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel()])
let section2 = CollectionViewSection(dataItems: [FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel(), FakeCollectionModel()])
let allSections = [section0, section1, section2]
var cellFactoryExpectation = self.expectationWithDescription("cell_factory_\(__FUNCTION__)")
// GIVEN: a cell factory
let cellFactory = CollectionViewCellFactory(reuseIdentifier: self.fakeCellReuseId) { (cell: FakeCollectionCell, model: FakeCollectionModel, view: UICollectionView, indexPath: NSIndexPath) -> FakeCollectionCell in
XCTAssertEqual(cell.reuseIdentifier, self.fakeCellReuseId, "Dequeued cell should have expected identifier")
XCTAssertEqual(view, self.fakeCollectionView, "CollectionView should equal the collectionView for the data source")
XCTAssertEqual(model, allSections[indexPath.section][indexPath.item], "Model object should equal expected value")
cellFactoryExpectation.fulfill()
return cell
}
var supplementaryFactoryExpectation = self.expectationWithDescription("supplementary_factory_\(__FUNCTION__)")
// GIVEN: a supplementary view factory
let supplementaryViewFactory = CollectionSupplementaryViewFactory(reuseIdentifier: self.fakeSupplementaryViewReuseId)
{ (view: FakeCollectionSupplementaryView, model: FakeCollectionModel, kind: String, collectionView: UICollectionView, indexPath: NSIndexPath) -> FakeCollectionSupplementaryView in
XCTAssertEqual(view.reuseIdentifier, self.fakeSupplementaryViewReuseId, "Dequeued supplementary view should have expected identifier")
XCTAssertEqual(collectionView, self.fakeCollectionView, "CollectionView should equal the collectionView for the data source")
XCTAssertEqual(model, allSections[indexPath.section][indexPath.item], "Model object should equal expected value")
supplementaryFactoryExpectation.fulfill()
return view
}
// GIVEN: a data source provider
let dataSourceProvider = CollectionViewDataSourceProvider(sections: allSections, cellFactory: cellFactory, supplementaryViewFactory: supplementaryViewFactory, collectionView: self.fakeCollectionView)
let dataSource = dataSourceProvider.dataSource
// WHEN: we call the collection view data source methods
let numSections = dataSource.numberOfSectionsInCollectionView?(self.fakeCollectionView)
// THEN: we receive the expected return values
XCTAssertNotNil(numSections, "Number of sections should not be nil")
XCTAssertEqual(numSections!, dataSourceProvider.sections.count, "Data source should return expected number of sections")
for sectionIndex in 0..<dataSourceProvider.sections.count {
for rowIndex in 0..<dataSourceProvider[sectionIndex].dataItems.count {
let expectationName = "\(__FUNCTION__)_\(sectionIndex)_\(rowIndex)"
self.fakeCollectionView.dequeueCellExpectation = self.expectationWithDescription(self.dequeueCellExpectationName + expectationName)
self.fakeCollectionView.dequeueSupplementaryViewExpectation = self.expectationWithDescription(self.dequeueSupplementaryViewExpectationName + expectationName)
let indexPath = NSIndexPath(forItem: rowIndex, inSection: sectionIndex)
// WHEN: we call the collection view data source methods
let numRows = dataSource.collectionView(self.fakeCollectionView, numberOfItemsInSection: sectionIndex)
let cell = dataSource.collectionView(self.fakeCollectionView, cellForItemAtIndexPath: indexPath)
let supplementaryView = dataSource.collectionView?(self.fakeCollectionView, viewForSupplementaryElementOfKind: FakeSupplementaryViewKind, atIndexPath: indexPath)
// THEN: we receive the expected return values
XCTAssertEqual(numRows, dataSourceProvider[sectionIndex].count, "Data source should return expected number of rows for section \(sectionIndex)")
XCTAssertEqual(cell.reuseIdentifier, self.fakeCellReuseId, "Data source should return cells with the expected identifier")
XCTAssertNotNil(supplementaryView, "Supplementary view should not be nil")
XCTAssertEqual(supplementaryView!.reuseIdentifier, self.fakeSupplementaryViewReuseId, "Data source should return supplementary views with the expected identifier")
// THEN: the collectionView calls `dequeueReusableCellWithReuseIdentifier`
// THEN: the cell factory calls its `ConfigurationHandler`
// THEN: the supplementary view factory calls its `ConfigurationHandler`
self.waitForExpectationsWithTimeout(1, handler: { (error) -> Void in
XCTAssertNil(error, "Expections should not error")
})
// reset expectation names for next loop, ignore last item
if !(sectionIndex == dataSourceProvider.sections.count - 1 && rowIndex == dataSourceProvider[sectionIndex].count - 1) {
cellFactoryExpectation = self.expectationWithDescription("cell_factory_" + expectationName)
supplementaryFactoryExpectation = self.expectationWithDescription("supplementary_factory_" + expectationName)
}
}
}
}
}
| 0da511852533e2ea24abee53a5a656a6 | 51.381089 | 250 | 0.742574 | false | false | false | false |
zcill/SwiftDemoCollection | refs/heads/master | Project 05-Basic TableView/Project5-Basic TableView/TableViewController.swift | mit | 1 | //
// TableViewController.swift
// Project5-Basic TableView
//
// Created by 朱立焜 on 16/4/13.
// Copyright © 2016年 朱立焜. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
let dataSource = ["Iron Man", "Spider Man", "Bat Man"]
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.leftBarButtonItem = 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 {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = dataSource[indexPath.row]
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false 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 false if you do not want the item to be re-orderable.
return true
}
}
| 524d43c8aa002fc7b4f1c48922aa1252 | 35.08 | 157 | 0.700665 | false | false | false | false |
tsaievan/XYReadBook | refs/heads/master | XYReadBook/XYReadBook/Classes/Views/Profile/XYBasicCell.swift | mit | 1 | //
// XYBasicCell.swift
// XYReadBook
//
// Created by tsaievan on 2017/9/4.
// Copyright © 2017年 tsaievan. All rights reserved.
//
import UIKit
class XYBasicCell: UITableViewCell {
var imgView = UIImageView()
var label = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
makeConstraints()
separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var model: XYElement? {
didSet {
imgView.image = UIImage(named: model?.img ?? "")
label.text = model?.title ?? ""
}
}
}
extension XYBasicCell {
func setupUI() {
imgView.contentMode = .center
imgView.layer.cornerRadius = 5
imgView.layer.masksToBounds = true
addSubview(imgView)
label.sizeToFit()
label.textColor = .darkGray
label.textAlignment = .center
addSubview(label)
}
}
extension XYBasicCell {
func makeConstraints() {
imgView.snp.makeConstraints { (make) in
make.width.equalTo(35)
make.height.equalTo(35)
make.top.equalTo(self).offset(8)
make.left.equalTo(self).offset(20)
}
label.snp.makeConstraints { (make) in
make.centerY.equalTo(self.imgView)
make.left.equalTo(imgView.snp.right).offset(16)
}
}
}
| a81e579d82909fcda88293c19c695b02 | 24.52381 | 77 | 0.590174 | false | false | false | false |
matrix-org/matrix-ios-sdk | refs/heads/develop | MatrixSDKTests/Crypto/MXOlmDeviceUnitTests.swift | apache-2.0 | 1 | //
// Copyright 2022 The Matrix.org Foundation C.I.C
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
@testable import MatrixSDK
class MXOlmDeviceUnitTests: XCTestCase {
/// Stubbed olm session that overrides first known index
class MXOlmSessionStub: MXOlmInboundGroupSession {
class OlmSessionStub: OLMInboundGroupSession {
override func firstKnownIndex() -> UInt {
return UInt.max
}
}
override var session: OLMInboundGroupSession! {
return OlmSessionStub()
}
}
/// Crypto store spy used to assert on for the test outcome
class CryptoStoreSpy: MXRealmCryptoStore {
var session: MXOlmInboundGroupSession?
override func inboundGroupSession(withId sessionId: String!, andSenderKey senderKey: String!) -> MXOlmInboundGroupSession! {
return session
}
override func store(_ sessions: [MXOlmInboundGroupSession]!) {
session = sessions.first
}
}
let senderKey = "ABC"
let roomId = "123"
var store: CryptoStoreSpy!
var device: MXOlmDevice!
override func setUp() {
super.setUp()
MXSDKOptions.sharedInstance().enableRoomSharedHistoryOnInvite = true
store = CryptoStoreSpy()
device = MXOlmDevice(store: store)
}
private func addInboundGroupSession(
sessionId: String,
sessionKey: String,
roomId: String,
sharedHistory: Bool
) {
device.addInboundGroupSession(
sessionId,
sessionKey: sessionKey,
roomId: roomId,
senderKey: senderKey,
forwardingCurve25519KeyChain: [],
keysClaimed: [:],
exportFormat: false,
sharedHistory: sharedHistory,
untrusted: false
)
}
func test_addInboundGroupSession_storesSharedHistory() {
let session = device.createOutboundGroupSessionForRoom(withRoomId: roomId)!
addInboundGroupSession(
sessionId: session.sessionId,
sessionKey: session.sessionKey,
roomId: roomId,
sharedHistory: true
)
XCTAssertNotNil(store.session)
XCTAssertTrue(store.session!.sharedHistory)
}
func test_addInboundGroupSession_doesNotOverrideSharedHistory() {
let session = device.createOutboundGroupSessionForRoom(withRoomId: roomId)!
// Add first inbound session that is not sharing history
addInboundGroupSession(
sessionId: session.sessionId,
sessionKey: session.sessionKey,
roomId: roomId,
sharedHistory: false
)
// Modify the now stored session so that it will be considered outdated
store.session = stubbedSession(for: store.session!)
// Add second inbound session with the same ID which is sharing history
addInboundGroupSession(
sessionId: session.sessionId,
sessionKey: session.sessionKey,
roomId: roomId,
sharedHistory: true
)
// After the update the shared history should not be changed
XCTAssertNotNil(store.session)
XCTAssertFalse(store.session!.sharedHistory)
}
func test_addMultipleInboundGroupSessions_doesNotOverrideSharedHistory() {
let session = device.createOutboundGroupSessionForRoom(withRoomId: roomId)!
// Add first inbound session that is not sharing history
addInboundGroupSession(
sessionId: session.sessionId,
sessionKey: session.sessionKey,
roomId: roomId,
sharedHistory: false
)
// Modify the now stored session so that it will be considered outdated
store.session = stubbedSession(for: store.session!)
// Add multiple sessions via exported data which are sharing history
let data = store.session!.exportData()!
data.sharedHistory = true
device.importInboundGroupSessions([data])
// After the update the shared history should not be changed
XCTAssertNotNil(store.session)
XCTAssertFalse(store.session!.sharedHistory)
}
// MARK: - Helpers
/// Create a stubbed version of olm session with custom index
private func stubbedSession(for session: MXOlmInboundGroupSession) -> MXOlmSessionStub {
let data = session.exportData()!
return MXOlmSessionStub(importedSessionData: data)!
}
}
| ff55d5f1f429a17e784387864764ee5b | 33.291391 | 132 | 0.638664 | false | false | false | false |
iOS-Connect/HackathonFeb2017 | refs/heads/master | PinVid/PinVid/ProfieList/DetailViewController.swift | mit | 1 | import UIKit
class DetailViewController: UIViewController {
var setLoop = false
lazy var start:Float = { Float(self.montage.clips.first!.start_time!) }()
lazy var end:Float = { Float(self.montage.clips.first!.end_time!) }()
var currentID: String!
var montage: Montage!
@IBOutlet var player: YTPlayerView!
override func viewDidLoad() {
super.viewDidLoad()
player.delegate = self
guard let url = montage.yt_url
else {
return
}
let comp = URLComponents(string: url)!
let id = comp.queryItems?.flatMap({ (item) -> String? in
if item.name == "v" {
return item.value
}
return nil
})
guard let ids = id, let first = ids.first else { return }
currentID = first
let playerVars = ["controls":0,"playsinline":1, "autohide":1, "showinfo":0, "modestbranding":1, "autoplay":1]
player.load(withVideoId: currentID, playerVars: playerVars)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
player.pauseVideo()
}
}
extension DetailViewController: YTPlayerViewDelegate {
func playerViewDidBecomeReady(_ playerView: YTPlayerView) {
playerView.loadVideo(byId: currentID, startSeconds: start, endSeconds: end, suggestedQuality: .small)
playerView.playVideo()
}
func playerView(_ playerView: YTPlayerView, didChangeTo state: YTPlayerState) {
print("changed to state \(state)")
}
func playerView(_ playerView: YTPlayerView, didChangeTo quality: YTPlaybackQuality) {
print("Quality \(quality)")
}
func playerView(_ playerView: YTPlayerView, receivedError error: YTPlayerError) {
print("got Error \(error)")
}
func playerView(_ playerView: YTPlayerView, didPlayTime playTime: Float) {
print("Played \(playTime)")
}
}
| d8ba961f1f04150cb9e569d5d571b7cb | 27.691176 | 117 | 0.631984 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Tool/Sources/ToolKit/General/Extensions/NumberFormatter+Conveniences.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
extension NumberFormatter {
// MARK: - Public Types
/// A currency format.
public enum CurrencyFormat {
/// If there are no fractional digits, the string would be shortened (e.g. `23.00` becomes `23`).
case shortened
/// The string would never be shortened (e.g. `23.00` stays `23.00`).
case fullLength
}
// MARK: - Setup
/// Creates a number formatter.
///
/// - Parameters:
/// - locale: A locale.
/// - currencyCode: A currency code.
/// - maxFractionDigits: The maximum number of digits after the decimal separator.
public convenience init(locale: Locale, currencyCode: String, maxFractionDigits: Int) {
self.init()
usesGroupingSeparator = true
roundingMode = .down
numberStyle = .currency
self.locale = locale
self.currencyCode = currencyCode
maximumFractionDigits = maxFractionDigits
}
// MARK: - Public Methods
/// Returns a string containing the formatted amount, optionally including the symbol.
///
/// - Parameters:
/// - amount: An amount in major units.
/// - includeSymbol: Whether the symbol should be included.
public func format(major amount: Decimal, includeSymbol: Bool) -> String {
let formattedString = string(from: NSDecimalNumber(decimal: amount)) ?? "\(amount)"
if !includeSymbol,
let firstDigitIndex = formattedString.firstIndex(where: { $0.inSet(characterSet: .decimalDigits) }),
let lastDigitIndex = formattedString.lastIndex(where: { $0.inSet(characterSet: .decimalDigits) })
{
return String(formattedString[firstDigitIndex...lastDigitIndex])
}
return formattedString
}
}
extension Character {
public func inSet(characterSet: CharacterSet) -> Bool {
CharacterSet(charactersIn: "\(self)").isSubset(of: characterSet)
}
}
| 35ad880886b368c87aa821e84a9bab07 | 32.9 | 111 | 0.636185 | false | false | false | false |
boycechang/BCColor | refs/heads/master | BCColor/HexColorViewController.swift | mit | 1 | //
// HexColorViewController.swift
// BCColorDemo
//
// Created by Boyce on 4/12/16.
// Copyright © 2016 Boyce. All rights reserved.
//
import UIKit
class HexColorViewController: UIViewController {
@IBOutlet fileprivate weak var label_1: UILabel!
@IBOutlet fileprivate weak var view_1: UIView!
@IBOutlet fileprivate weak var label_2: UILabel!
@IBOutlet fileprivate weak var view_2: UIView!
@IBOutlet fileprivate weak var label_3: UILabel!
@IBOutlet fileprivate weak var view_3: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
label_1.text = "123456"
view_1.backgroundColor = UIColor.colorWithHex("123456")
label_2.text = "#5d13e2"
view_2.backgroundColor = UIColor.colorWithHex("#5d13e2", alpha: 1)
label_3.text = "#931"
view_3.backgroundColor = UIColor.colorWithHex("#931", alpha: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 1dbef7e053fc86cecec88e35625aac63 | 28.056604 | 106 | 0.653896 | false | false | false | false |
gemtot/iBeacon | refs/heads/master | GemTotSDK/GemTotSDK/Views/GTBeaconTableViewController.swift | gpl-3.0 | 1 | //
// GTBeaconTableViewController.swift
// GemTotSDK
//
// Copyright (c) 2014 PassKit, Inc.
//
// 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
class GTBeaconTableViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
// Constants - form elements
let _toggleSwitch : UISwitch = UISwitch()
let _dbPicker : UIPickerView = UIPickerView()
let _numberToolbar : UIToolbar = UIToolbar(frame: CGRectMake(0.0,0.0,320.0,50.0))
// Shared objects
let _iBeaconConfig : GTStorage = GTStorage.sharedGTStorage // Dictionary containing beacon config parameters
let _beacon : GTBeaconBroadcaster = GTBeaconBroadcaster.sharedGTBeaconBroadcaster // Shared instance to allow continuous broadcasting after this view is dismissed
override func viewDidLoad() {
super.viewDidLoad()
// Preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
// Subscribe to notifications on toggle changes
NSNotificationCenter.defaultCenter().addObserver(self, selector: "toggleStatus:", name: "iBeaconBroadcastStatus", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onKeyboardHide:", name: UIKeyboardDidHideNotification, object: nil)
// Conifgure the toolbar and pickerview
configureToolbarToggleAndPicker()
// Add a gesture recognizer to make dismissing the keyboard easier
addTapGestureRecognizers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**************************************************************************************
*
* Helper Functions
*
**************************************************************************************/
// Configures the view components ready for viewing
func configureToolbarToggleAndPicker() {
// Configure the toolbar that sits above the numeric keypad
let toolbarButtonItems = [
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: NSLocalizedString("Done", comment: "Button to accept the iBeacon paramaters and dismiss the keyboard"), style: .Plain, target: self, action: "dismissKeyboard:")
]
_numberToolbar.setItems(toolbarButtonItems, animated:false)
_numberToolbar.barStyle = UIBarStyle.Default
_numberToolbar.translucent = true
_numberToolbar.sizeToFit()
// Configure the date picker
_dbPicker.dataSource = self;
_dbPicker.delegate = self;
_dbPicker.backgroundColor = UIColor.whiteColor()
// Configure the toggle
_toggleSwitch.setOn(_beacon.beaconStatus(), animated: false)
_toggleSwitch.addTarget(self, action: "toggleBeacon:", forControlEvents: UIControlEvents.ValueChanged)
}
// Adds a tap gesture to the background to dismiss the keyboard if users click outside of the keyboard of input cells and a tap gesture to the table footer to copy the UUID to the clipboard
func addTapGestureRecognizers() {
let tapBackground : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard:")
self.view.addGestureRecognizer(tapBackground)
}
// Copy the UUID to the clipboard
func copyUUID(sender: AnyObject) {
let UUID = _iBeaconConfig.getValue("UUID", fromStore:"iBeacon") as! String
let pasteBoard: UIPasteboard = UIPasteboard.generalPasteboard()
pasteBoard.string = UUID
let alert = UIAlertController(title: NSLocalizedString("UUID copied clipboard", comment:"Alert UUID Copied to Clipboard"), message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.message = "\n" + UUID
alert.addAction(UIAlertAction(title: NSLocalizedString("Okay", comment:"OK button used to dismiss alerts"), style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
// callback funciton called whenever the toggle changes state
func toggleBeacon(sender :AnyObject!) {
let button = sender as! UISwitch
let state = button.on
if (state == true) {
let beaconStarted = _beacon.startBeacon()
if (beaconStarted.success == false) {
_toggleSwitch.setOn(false, animated: false)
let alert = UIAlertController(title: NSLocalizedString("Error Starting Beacon", comment:"Alert title for problemn starting beacon"), message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.message = beaconStarted.error as? String
alert.addAction(UIAlertAction(title: NSLocalizedString("Okay", comment:"OK button used to dismiss alerts"), style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
} else {
_beacon.stopBeacon()
}
// Reload the table to update the table footer message
self.tableView.reloadData()
}
func toggleStatus(notification: NSNotification) {
let packageContents : NSDictionary = notification.userInfo! as Dictionary
_toggleSwitch.setOn(packageContents.objectForKey("broadcastStatus") as! Bool, animated: false)
if (packageContents.objectForKey("broadcastStatus") as! Bool) {
if (!_beacon.beaconStatus()) {
_beacon.startBeacon()
}
}
self.tableView.reloadData()
}
// Utility function to construct the footer message containin the advertising paramaters
func footerString() -> String {
let UUID = _iBeaconConfig.getValue("UUID", fromStore:"iBeacon") as! String
// Hack to ensure toggle is correctly set on first startup
_toggleSwitch.setOn(_beacon.beaconStatus(), animated: false)
// If the device is broadcasting, construct a string containing the advertising paramaters
if (_beacon.beaconStatus() == true) {
// retrieve the current values from the config dictionary
let major = _iBeaconConfig.getValue("major", fromStore:"iBeacon") as! NSNumber
let minor = _iBeaconConfig.getValue("minor", fromStore:"iBeacon") as! NSNumber
let power = _iBeaconConfig.getValue("power", fromStore: "iBeacon") as! NSNumber
// Construct a readable string from the power value
var powerString : String
if (power.integerValue == 127) {
powerString = NSLocalizedString("Device Default", comment:"Label shown in table cell to indicate deivce will broadcast the default measured power")
} else {
let sign = (power.integerValue <= 0 ? "" : "+")
powerString = "\(sign)\(power)dB"
}
// Put it all together
let footerString = String.localizedStringWithFormat(NSLocalizedString("Broadcasting beacon signal\n\nUUID: %@\nMajor: %@; Minor: %@\nMeasured Power: %@", comment:"Structured message to display the paramaters of the beacon signal that is currently being broadcast"), UUID, major, minor, powerString)
return footerString
} else {
let footerString = String.localizedStringWithFormat(NSLocalizedString("UUID: %@\n\nThis device is not broadcasting a beacon signal", comment:"Text at bottom of iBeacon view when not broadcasting an iBeacon signal"), UUID)
return footerString
}
}
func dismissKeyboard(sender: AnyObject) {
self.view.endEditing(true)
}
// Reloads the table to update the footer message whenever the keyboard is dismissed
func onKeyboardHide(notification: NSNotification!) {
self.tableView.reloadData()
}
// Function to check if string is a UUID, or to generate a constant UUID from a string
func UUIDforString(UUIDNameOrString: String) -> String {
// Test if UUIDNameOrString is a valid UUID, and if so, set the return it
let range = UUIDNameOrString.rangeOfString("^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[1-5][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$", options: .RegularExpressionSearch)
if (range != nil && UUIDNameOrString.characters.count == 36) {
return UUIDNameOrString
} else {
//var ccount: UInt16 = 16 + UUIDNameOrString.characters.count.value as UInt16
// Variable to hold the hashed namespace
let hashString = NSMutableData()
// Unique seed namespace - keep to generate UUIDs compatible with PassKit, or change to avoid conflicts
// Needs to be a hexadecimal value - ideally a UUID
let nameSpace: String = "b8672a1f84f54e7c97bdff3e9cea6d7a"
// Convert each byte of the seed namespace to a character value and append the character byte
for var i = 0; i < nameSpace.characters.count; i+=2 {
var charValue: UInt32 = 0
let s = "0x" + String(Array(nameSpace.characters)[i]) + String(Array(nameSpace.characters)[i+1])
NSScanner(string: s).scanHexInt(&charValue)
hashString.appendBytes(&charValue, length: 1)
}
// Append the UUID String bytes to the hash input
let uuidString: NSData = NSString(format:UUIDNameOrString, NSUTF8StringEncoding).dataUsingEncoding(NSUTF8StringEncoding)!
hashString.appendBytes(uuidString.bytes, length: uuidString.length)
// SHA1 hash the input
let rawUUIDString = String(hashString.sha1())
// Build the UUID string as defined in RFC 4122
var part3: UInt32 = 0
var part4: UInt32 = 0
NSScanner(string: (rawUUIDString as NSString).substringWithRange(NSMakeRange(12, 4))).scanHexInt(&part3)
NSScanner(string: (rawUUIDString as NSString).substringWithRange(NSMakeRange(16, 4))).scanHexInt(&part4)
let uuidPart3 = String(NSString(format:"%2X", (part3 & 0x0FFF) | 0x5000))
let uuidPart4 = String(NSString(format:"%2X", (part4 & 0x3FFF) | 0x8000))
return "\((rawUUIDString as NSString).substringWithRange(NSMakeRange(0, 8)))-" +
"\((rawUUIDString as NSString).substringWithRange(NSMakeRange(8, 4)))-" +
"\(uuidPart3.lowercaseString)-" +
"\(uuidPart4.lowercaseString)-" +
"\((rawUUIDString as NSString).substringWithRange(NSMakeRange(20, 12)))"
}
}
/**************************************************************************************
*
* UITable View Delegate Functions
*
**************************************************************************************/
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 2
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
if (section == 0) {
return 1
} else {
return 4
}
}
override func tableView(tableView: UITableView?, didSelectRowAtIndexPath indexPath: NSIndexPath?) {
tableView!.userInteractionEnabled = false
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.section == 0) {
let cell :UITableViewCell? = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "iBeaconToggle")
// Add the image to the table cell
let cellImage = UIImage(named:"iBeaconTableCell")
if let imageView = cell?.imageView {
imageView.image = cellImage
} else {
NSLog("imageView is nil")
}
// Set the cell label
if let textLabel = cell?.textLabel {
textLabel.text = NSLocalizedString("Broadcast Signal", comment:"Label of iBeacon Toggle to start or stop broadcasting as an iBeacon") as String
textLabel.font = UIFont.systemFontOfSize(16.0)
} else {
NSLog("textLabel is nil")
}
// Add the toggle to the table cell and
cell?.accessoryView = UIView(frame: _toggleSwitch.frame)
if let accessoryView = cell?.accessoryView {
accessoryView.addSubview(_toggleSwitch)
} else {
NSLog("accessoryView is nil")
}
// Make the cell non-selectable (only the toggle will be active)
cell?.selectionStyle = UITableViewCellSelectionStyle.None
return cell!
} else {
let cell :UITableViewCell? = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "iBeaconCell")
let iBeaconParamsLabels = [
NSLocalizedString("Name or UUID", comment:"Tabel cell label for beacon name or UUID value"),
NSLocalizedString("Major Value", comment:"Table cell label for beacon major value"),
NSLocalizedString("Minor Value", comment:"Table cell label for beacon minor value"),
NSLocalizedString("Measured Power", comment:"Table cell label for beacon measured power value")
]
// Set the cell label
if let textLabel = cell?.textLabel {
textLabel.text = iBeaconParamsLabels[indexPath.row]
textLabel.font = UIFont.systemFontOfSize(16.0)
} else {
NSLog("textLabel is nil")
}
// Create and add a text field to the cell that will contain the value
let optionalMargin: CGFloat = 10.0
let valueField = UITextField(frame: CGRectMake(170, 10, cell!.contentView.frame.size.width - 170 - optionalMargin, cell!.contentView.frame.size.height - 10 - optionalMargin))
valueField.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
valueField.delegate = self
valueField.returnKeyType = UIReturnKeyType.Done
valueField.clearButtonMode = UITextFieldViewMode.WhileEditing
valueField.font = UIFont.systemFontOfSize(16.0)
cell?.contentView.addSubview(valueField)
switch (indexPath.row) {
// Populate the value for each cell and configure the field UI as apporpriate for each value type
case 0:
valueField.text = _iBeaconConfig.getValue("beaconName", fromStore: "iBeacon") as? String
valueField.placeholder = NSLocalizedString("Name or UUID", comment:"Placehoder text for iBeacon name field")
valueField.tag = 1
case 1:
valueField.text = (_iBeaconConfig.getValue("major", fromStore: "iBeacon") as! NSNumber).stringValue
valueField.placeholder = NSLocalizedString("0 - 65,535", comment:"iBeacon Major and Minor placehoder (represents min and max values)")
valueField.keyboardType = UIKeyboardType.NumberPad
valueField.inputAccessoryView = _numberToolbar
valueField.tag = 2
case 2:
valueField.text = (_iBeaconConfig.getValue("minor", fromStore: "iBeacon") as! NSNumber).stringValue
valueField.placeholder = NSLocalizedString("0 - 65,535", comment:"iBeacon Major and Minor placehoder (represents min and max values)")
valueField.keyboardType = UIKeyboardType.NumberPad
valueField.inputAccessoryView = _numberToolbar
valueField.tag = 3
case 3:
let powerValue = _iBeaconConfig.getValue("power", fromStore: "iBeacon") as! Int
if (powerValue == 127) {
valueField.text = NSLocalizedString("Device Default", comment:"Label shown in table cell to indicate deivce will broadcast the default measured power")
} else {
let sign = (powerValue <= 0 ? "" : "+")
valueField.text = "\(sign)\(powerValue)dB"
}
valueField.tag = 4
valueField.inputView = _dbPicker
valueField.inputAccessoryView = _numberToolbar
valueField.clearButtonMode = UITextFieldViewMode.Never
valueField.tintColor = UIColor.clearColor() // This will hide the flashing cursor
default:
break
}
return cell!
}
}
//Override to support conditional editing of the table view.
override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
return false
}
//Override to support custom section headers.
override func tableView(tableView: UITableView?, titleForHeaderInSection section: Int) -> String? {
if (section == 0) {
return NSLocalizedString("Beacon Status", comment: "Header of first section of iBeacon view")
} else if (section == 1) {
return NSLocalizedString("Beacon Paramaers", comment: "Header of second section of iBeacon view")
}
return nil
}
override func tableView(tableView: UITableView?, viewForFooterInSection section: Int) -> UIView? {
if (section == 1) {
let label: UILabel = UILabel()
label.userInteractionEnabled = true
label.text = footerString()
label.baselineAdjustment = UIBaselineAdjustment.AlignBaselines;
label.font = UIFont.systemFontOfSize(UIFont.smallSystemFontSize())
label.textColor = UIColor.grayColor()
label.numberOfLines = 0
label.sizeToFit()
var frame: CGRect = label.frame
let view: UIView = UIView()
view.frame = frame
// Add padding to align label to Table View
frame.origin.x = 15;
frame.origin.y = 5;
frame.size.width = self.view.bounds.size.width - frame.origin.x;
frame.size.height = frame.size.height + frame.origin.y;
label.frame = frame;
view.addSubview(label)
view.sizeToFit()
// Add a Gesture Recognizer to copy the UUID to the Clipboard
let tapTableFooter : UITapGestureRecognizer = UITapGestureRecognizer (target: self, action: "copyUUID:")
tapTableFooter.numberOfTapsRequired = 1
label.addGestureRecognizer(tapTableFooter)
return view
}
return nil
}
override func tableView(tableView: UITableView?, heightForFooterInSection section: Int) -> CGFloat {
if (section == 1) {
return 100;
}
return 0;
}
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView?, canMoveRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
return false
}
/**************************************************************************************
*
* UIPickerView Data Source and Delegate Functions
*
**************************************************************************************/
func pickerView(_: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if (row == 0) {
// Set the first row of the picker view as an option to select the device default measured power
return NSLocalizedString("Use Device Default Value", comment:"Description for selecting the device default power, shown on the pickser wheel. Should be kept concise")
} else {
// Construct the a string to return. Negative values will already be prexied with a minus sign
let sign = (row < 102 ? "" : "+")
return "\(sign)\(row - 101)dB"
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
// -100dB to +100dB inclusive plus an option to select device default measured power
return 202
}
/**************************************************************************************
*
* UITextField Delegate Functions
*
**************************************************************************************/
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Dismiss the keyboard
textField.resignFirstResponder()
return true
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
switch (textField.tag) {
case 1:
// Replace empty string with a default value
if (textField.text == "") {
textField.text = "GemTot iOS"
}
case 2...3:
// Validate the major and minor values before accepting. If invalid, throw an alert and empty the field
if (Int(textField.text!) > 0xFFFF) {
let alert = UIAlertController(title: NSLocalizedString("Invalid Value", comment:"Alert title for invalid values"), message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.message = NSLocalizedString("Major and Minor keys can only accept a value between 0 and 65,535", comment:"Alert message to show if user enters an invalid Major or Minor value")
alert.addAction(UIAlertAction(title: NSLocalizedString("Okay", comment:"OK button used to dismiss alerts"), style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
textField.text = ""
return false
}
// If an empty filed is submitted, replace with a 0 value
if (textField.text == "") {
textField.text = "0"
return true
}
case 4:
// Check if the picker view value is different to the field value and if so, update the field value and the config dictionary
let row = _dbPicker.selectedRowInComponent(0)
var targetText = ""
if (row == 0) {
targetText = NSLocalizedString("Device Default", comment:"Label shown in table cell to indicate deivce will broadcast the default measured power")
} else {
targetText = self.pickerView(_dbPicker, titleForRow: row, forComponent: 0)!
}
if (textField.text != targetText) {
textField.text = targetText
let dBValue: NSNumber = (row == 0 ? 127 : row - 101)
_iBeaconConfig.writeValue(dBValue as NSNumber, forKey: "power", toStore: "iBeacon")
}
default:
return true
}
return true
}
func textFieldDidEndEditing(textField: UITextField) {
// Store the updated values in the config dictionary
switch (textField.tag) {
case 1:
_iBeaconConfig.writeValue(textField.text, forKey:"beaconName", toStore:"iBeacon")
_iBeaconConfig.writeValue(UUIDforString(textField.text!), forKey:"UUID", toStore:"iBeacon")
case 2:
_iBeaconConfig.writeValue(Int(textField.text!)!, forKey: "major", toStore: "iBeacon")
case 3:
_iBeaconConfig.writeValue(Int(textField.text!)!, forKey: "minor", toStore: "iBeacon")
default:
break
}
// If the beacon is broadcasting - dispatch a job to restart the beacon which will pick up the new values
if (_toggleSwitch.on) {
dispatch_async(dispatch_get_main_queue(), {_ = self._beacon.startBeacon()})
}
// Dismiss the keyboard
textField.resignFirstResponder()
}
@IBAction func openSourceCode(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://github.com/gemtot")!)
}
@IBAction func buyBeacons(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://gemtot.com/")!)
}
} | 874bf345cff011e6e787f23e84a95ce4 | 42.778523 | 310 | 0.593921 | false | false | false | false |
SwiftKit/Lipstick | refs/heads/master | Source/UIEdgeInsets+Init.swift | mit | 1 | //
// UIEdgeInsets+Init.swift
// Lipstick
//
// Created by Filip Dolnik on 16.10.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import UIKit
extension UIEdgeInsets {
public init(left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) {
self.init(top: 0, left: left, bottom: bottom, right: right)
}
public init(top: CGFloat, bottom: CGFloat = 0, right: CGFloat = 0) {
self.init(top: top, left: 0, bottom: bottom, right: right)
}
public init(top: CGFloat, left: CGFloat, right: CGFloat = 0) {
self.init(top: top, left: left, bottom: 0, right: right)
}
public init(top: CGFloat, left: CGFloat, bottom: CGFloat) {
self.init(top: top, left: left, bottom: bottom, right: 0)
}
public init(_ all: CGFloat) {
self.init(horizontal: all, vertical: all)
}
public init(horizontal: CGFloat, vertical: CGFloat) {
self.init(top: vertical, left: horizontal, bottom: vertical, right: horizontal)
}
public init(horizontal: CGFloat, top: CGFloat = 0, bottom: CGFloat = 0) {
self.init(top: top, left: horizontal, bottom: bottom, right: horizontal)
}
public init(vertical: CGFloat, left: CGFloat = 0, right: CGFloat = 0) {
self.init(top: vertical, left: left, bottom: vertical, right: right)
}
}
| ff744cbc2fa5a8f939def1b282d44ea6 | 29.909091 | 87 | 0.616176 | false | false | false | false |
KeithPiTsui/Pavers | refs/heads/swift5 | Pavers/Sources/FRP/Functional/Types/Lens/Lens.swift | mit | 1 | public struct Lens <Whole, Part> {
public let view: (Whole) -> Part
public let set: (Part, Whole) -> Whole
public init(view: @escaping (Whole) -> Part, set: @escaping (Part, Whole) -> Whole) {
self.view = view
self.set = set
}
/**
Map a function over a part of a whole.
- parameter f: A function.
- returns: A function that takes wholes to wholes by applying the function to a subpart.
*/
public func over(_ f: @escaping (Part) -> Part) -> ((Whole) -> Whole) {
return { whole in
let part = self.view(whole)
return self.set(f(part), whole)
}
}
/**
Composes two lenses. Given lenses `Lens<A, B>` and `Lens<B, C>` it is possible to construct a lens
`Lens<A, C>`.
- parameter rhs: Another lens.
- returns: A composed lens.
*/
public func compose<Subpart>(_ rhs: Lens<Part, Subpart>) -> Lens<Whole, Subpart> {
return Lens<Whole, Subpart>(
view: self.view >>> rhs.view,
set: { subPart, whole in
let part = self.view(whole)
let newPart = rhs.set(subPart, part)
return self.set(newPart, whole)
})
}
}
public extension Lens where Part : Comparable {
/// Constructs a comparator on `Whole` when `Part` conforms to `Comparable`.
var comparator: Comparator<Whole> {
return Comparator { lhs, rhs in
self.view(lhs) < self.view(rhs) ? .lt
: self.view(lhs) == self.view(rhs) ? .eq
: .gt
}
}
}
/**
Infix operator of the `set` function.
- parameter lens: A lens.
- parameter part: A part.
- returns: A function that transforms a whole into a new whole with a part replaced.
*/
public func .~ <Whole, Part> (lens: Lens<Whole, Part>, part: Part) -> ((Whole) -> Whole) {
return { whole in lens.set(part, whole) }
}
/**
Infix operator of the `view` function.
- parameter whole: A whole.
- parameter lens: A lens.
- returns: A part of a whole when viewed through the lens provided.
*/
public func ^* <Whole, Part> (whole: Whole, lens: Lens<Whole, Part>) -> Part {
return lens.view(whole)
}
/**
Infix operator of `compose`, which composes two lenses.
- parameter lhs: A lens.
- parameter rhs: A lens.
- returns: The composed lens.
*/
public func >>> <A, B, C> (lhs: Lens<A, B>, rhs: Lens<B, C>) -> Lens<A, C> {
return lhs.compose(rhs)
}
/**
Infix operator of Kleisli composition. This type of composition can help avoid need the full power of
prisms and traversals when all you need to do is compose lenses through an optional value.
- parameter lhs: A lens whose part is optional.
- parameter rhs: A lens whose part is optional.
- returns: The composed lens.
*/
public func >>> <A, B, C> (lhs: Lens<A, B?>, rhs: Lens<B, C?>) -> Lens<A, C?> {
return Lens(
view: { a in lhs.view(a).flatMap(rhs.view) },
set: { (c, a) in lhs.set(lhs.view(a).map { rhs.set(c, $0) }, a) }
)
}
/**
Infix operator of the `over` function.
- parameter lens: A lens.
- parameter f: A function for transforming a part of a whole.
- returns: A function that transforms a whole into a new whole with its part transformed by `f`.
*/
public func %~ <Whole, Part> (lens: Lens<Whole, Part>, f: @escaping (Part) -> Part) -> ((Whole) -> Whole) {
return lens.over(f)
}
/**
Variation of the infix operator %~.
- parameter lens: A lens.
- parameter f: A function for transforming a part and whole into a new part.
- returns: A function that transforms a whole into a new whole with its part transformed by `f`.
*/
public func %~~ <Whole, Part> (lens: Lens<Whole, Part>,
f: @escaping (Part, Whole) -> Part) -> ((Whole) -> Whole) {
return { whole in
let part = lens.view(whole)
return lens.set(f(part, whole), whole)
}
}
/**
Infix operator to transform a part of a whole with a semigroup operation.
- parameter lens: A lens whose part is a semigroup.
- parameter a: A part value that is concatenated to the part of a whole.
- returns: A function that transform a whole into a new whole with its part concatenated to `a`.
*/
public func <>~ <Whole, Part: Semigroup> (lens: Lens<Whole, Part>, a: Part) -> ((Whole) -> Whole) {
return lens.over(>>>a)
}
| 3ca87f53cadcb4ccba2648169af65cd1 | 27.834483 | 107 | 0.633102 | false | false | false | false |
stephentyrone/swift | refs/heads/master | test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_same_generic_class_same_value.swift | apache-2.0 | 1 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5Value[[UNIQUE_ID_1:[0-9A-Z_]+]]LLCyAA9Argument1ACLLCySiGAGGMf" = linkonce_odr hidden
// CHECK-apple-SAME: global
// CHECK-unknown-SAME: constant
// CHECK-SAME: <{
// CHECK-SAME: void (%T4main5Value[[UNIQUE_ID_1]]LLC*)*,
// CHECK-SAME: i8**,
// : [[INT]],
// CHECK-apple-SAME: %objc_class*,
// CHECK-unknown-SAME: %swift.type*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: [[INT]],
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i16,
// CHECK-SAME: i16,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: i8*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-apple-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* (
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.type*
// CHECK-SAME: )*
// CHECK-SAME: }> <{
// CHECK-SAME: void (%T4main5Value[[UNIQUE_ID_1]]LLC*)*
// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCfD
// CHECK-SAME: $sBoWV
// CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCyAA9Argument1ACLLCySiGAGGMM
// CHECK-apple-SAME: OBJC_CLASS_$__TtCs12_SwiftObject
// CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-apple-SAME: %swift.opaque* null,
// CHECK-apple-SAME: [[INT]] add (
// CHECK-apple-SAME: [[INT]] ptrtoint (
// CHECK-apple-SAME: {
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// : i32,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: {
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: [
// CHECK-apple-SAME: 2 x {
// CHECK-apple-SAME: [[INT]]*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32
// CHECK-apple-SAME: }
// CHECK-apple-SAME: ]
// CHECK-apple-SAME: }*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*
// CHECK-apple-SAME: }* @_DATA__TtC4mainP[[UNIQUE_ID_2:[0-9A-Z_]+]]5Value to [[INT]]
// CHECK-apple-SAME: ),
// CHECK-apple-SAME: [[INT]] 2
// CHECK-apple-SAME: ),
// CHECK-unknown-SAME: [[INT]] 0,
// CHECK-unknown-SAME: %swift.type* null,
// CHECK-SAME: i32 26,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 {{(32|16)}},
// CHECK-SAME: i16 {{(7|3)}},
// CHECK-SAME: i16 0,
// CHECK-apple-SAME: i32 {{(136|80)}},
// CHECK-unknown-SAME: i32 112,
// CHECK-SAME: i32 {{(16|8)}},
// : %swift.type_descriptor* bitcast (
// : <{
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i16,
// : i16,
// : i8,
// : i8,
// : i8,
// : i8,
// : i32,
// : i32,
// : %swift.method_descriptor
// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn
// : ),
// CHECK-SAME: i8* null,
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_heapmetadata,
// CHECK-SAME: %swift.full_heapmetadata* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main9Argument1[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: )*,
// CHECK-SAME: i8**,
// : [[INT]],
// CHECK-apple-SAME: %objc_class*,
// CHECK-unknown-SAME: %swift.type*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: [[INT]],
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i16,
// CHECK-SAME: i16,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: i8*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %T4main9Argument1[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: )*
// CHECK-SAME: }>* @"$s4main9Argument1[[UNIQUE_ID_1]]LLCySiGMf" to %swift.full_heapmetadata*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 2
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_heapmetadata,
// CHECK-SAME: %swift.full_heapmetadata* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main9Argument1[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: )*,
// CHECK-SAME: i8**,
// : [[INT]],
// CHECK-apple-SAME: %objc_class*,
// CHECK-unknown-SAME: %swift.type*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: [[INT]],
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i16,
// CHECK-SAME: i16,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: i8*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %T4main9Argument1[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: )*
// CHECK-SAME: }>* @"$s4main9Argument1[[UNIQUE_ID_1]]LLCySiGMf" to %swift.full_heapmetadata*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 2
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] {{(16|8)}},
// CHECK-SAME: [[INT]] {{(24|12)}},
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLC5first6secondADyxq_Gx_q_tcfC
// CHECK-SAME: }>,
// CHECK-SAME: align [[ALIGNMENT]]
fileprivate class Value<First, Second> {
let first: First
let second: Second
init(first: First, second: Second) {
self.first = first
self.second = second
}
}
fileprivate class Argument1<Value> {
let value: Value
init(value: Value) {
self.value = value
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4:[0-9A-Z_]+]]LLCyAA9Argument1ACLLCySiGAGGMb"([[INT]] 0)
// CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}},
// CHECK-SAME: %swift.type* [[METADATA]])
// CHECK: }
func doit() {
consume( Value(first: Argument1(value: 13), second: Argument1(value: 13)) )
}
doit()
// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], %swift.type* [[ARGUMENT1_METADATA:%[0-9]+]], %swift.type* [[ARGUMENT2_METADATA:%[0-9]+]]) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_ARGUMENT1:%[0-9]+]] = bitcast %swift.type* [[ARGUMENT1_METADATA]] to i8*
// CHECK: [[ERASED_ARGUMENT2:%[0-9]+]] = bitcast %swift.type* [[ARGUMENT2_METADATA]] to i8*
// CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_LABEL]]:
// CHECK: [[EQUAL_TYPE_1:%[0-9]+]] = icmp eq i8* bitcast (
// : %swift.type* getelementptr inbounds (
// : %swift.full_heapmetadata,
// : %swift.full_heapmetadata* bitcast (
// : <{
// : void (
// : %T4main9Argument1[[UNIQUE_ID_1]]LLC*
// : )*,
// : i8**,
// : [[INT]],
// : %objc_class*,
// : %swift.opaque*,
// : %swift.opaque*,
// : [[INT]],
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i32,
// : i32,
// : %swift.type_descriptor*,
// : i8*,
// : %swift.type*,
// : [[INT]],
// : %T4main9Argument1[[UNIQUE_ID_1]]LLC* (
// : %swift.opaque*,
// : %swift.type*
// : )*
// : }>*
// CHECK-SAME: @"$s4main9Argument1[[UNIQUE_ID_1]]LLCySiGMf"
// : to %swift.full_heapmetadata*
// : ),
// : i32 0,
// : i32 2
// : ) to i8*
// CHECK-SAME: ), [[ERASED_ARGUMENT1]]
// CHECK: [[EQUAL_TYPES_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1]]
// CHECK: [[EQUAL_TYPE_2:%[0-9]+]] = icmp eq i8* bitcast (
// : %swift.type* getelementptr inbounds (
// : %swift.full_heapmetadata,
// : %swift.full_heapmetadata* bitcast (
// : <{
// : void (
// : %T4main9Argument1[[UNIQUE_ID_1]]LLC*
// : )*,
// : i8**,
// : [[INT]],
// : %objc_class*,
// : %swift.opaque*,
// : %swift.opaque*,
// : [[INT]],
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i32,
// : i32,
// : %swift.type_descriptor*,
// : i8*,
// : %swift.type*,
// : [[INT]],
// : %T4main9Argument1[[UNIQUE_ID_1]]LLC* (
// : %swift.opaque*,
// : %swift.type*
// : )*
// CHECK-SAME: }>* @"$s4main9Argument1[[UNIQUE_ID_1]]LLCySiGMf" to %swift.full_heapmetadata*
// : ),
// : i32 0,
// : i32 2
// : ) to i8*
// : ), [[ERASED_ARGUMENT2]]
// CHECK: [[EQUAL_TYPES_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1]], [[EQUAL_TYPE_2]]
// CHECK: br i1 [[EQUAL_TYPES_2]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED]]:
// CHECK-NEXT: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_3:[0-9A-Z_]+]]LLCyAA9Argument1ACLLCySiGAGGMb"([[INT]] [[METADATA_REQUEST]])
// CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0
// CHECK: [[PARTIAL_RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[METADATA]], 0
// CHECK: [[RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_RESULT_METADATA]], [[INT]] 0, 1
// CHECK: ret %swift.metadata_response [[RESULT_METADATA]]
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK: [[INT]] [[METADATA_REQUEST]],
// CHECK: i8* [[ERASED_ARGUMENT1]],
// CHECK: i8* [[ERASED_ARGUMENT2]],
// CHECK: i8* undef,
// CHECK: %swift.type_descriptor* bitcast (
// : <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, %swift.method_descriptor }>*
// CHECK: $s4main5Value[[UNIQUE_ID_1]]LLCMn
// CHECK: to %swift.type_descriptor*
// CHECK: )
// CHECK: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4]]LLCyAA9Argument1ACLLCySiGAGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]}} {
// CHECK: entry:
// CHECK: call swiftcc %swift.metadata_response @"$s4main9Argument1[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0)
// CHECK-NOT: call swiftcc %swift.metadata_response @"$s4main9Argument1[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0)
// CHECK-unknown: ret
// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call %objc_class* @objc_opt_self(
// : %objc_class* bitcast (
// : %swift.type* getelementptr inbounds (
// : %swift.full_heapmetadata,
// : %swift.full_heapmetadata* bitcast (
// : <{
// : void (
// : %T4main5Value[[UNIQUE_ID_1]]LLC*
// : )*,
// : i8**,
// : [[INT]],
// : %objc_class*,
// : %swift.opaque*,
// : %swift.opaque*,
// : [[INT]],
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i32,
// : i32,
// : %swift.type_descriptor*,
// : i8*,
// : %swift.type*,
// : %swift.type*,
// : [[INT]],
// : [[INT]],
// : %T4main5Value[[UNIQUE_ID_1]]LLC* (
// : %swift.opaque*,
// : %swift.opaque*,
// : %swift.type*
// : )*
// : }>*
// CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA9Argument1ACLLCySiGAGGMf"
// : to %swift.full_heapmetadata*
// : ),
// : i32 0,
// : i32 2
// : ) to %objc_class*
// : )
// : )
// CHECK-apple: [[INITIALIZED_METADATA:%[0-9]+]] = bitcast %objc_class* [[INITIALIZED_CLASS]] to %swift.type*
// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[INITIALIZED_METADATA]], 0
// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1
// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]]
// CHECK: }
| d5ff3720e77ee24900545c79a4c764cf | 43.729659 | 242 | 0.423777 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformKit/Services/NabuAuthentication/WalletNabuSynchronizerService.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import FeatureAuthenticationDomain
import NetworkKit
import ToolKit
public enum WalletNabuSynchronizerServiceError: Error {
case failedToRetrieveToken
case failedToUpdateWalletInfo
}
/// Protocol definition for a component that can synchronize state between the wallet
/// and Nabu.
public protocol WalletNabuSynchronizerServiceAPI {
func sync() -> AnyPublisher<Void, WalletNabuSynchronizerServiceError>
}
final class WalletNabuSynchronizerService: WalletNabuSynchronizerServiceAPI {
// MARK: - Properties
private let jwtService: JWTServiceAPI
private let updateUserInformationClient: UpdateWalletInformationClientAPI
// MARK: - Setup
init(
jwtService: JWTServiceAPI = resolve(),
updateUserInformationClient: UpdateWalletInformationClientAPI = resolve()
) {
self.jwtService = jwtService
self.updateUserInformationClient = updateUserInformationClient
}
// MARK: - Methods
func sync() -> AnyPublisher<Void, WalletNabuSynchronizerServiceError> {
let updateUserInformationClient = updateUserInformationClient
return jwtService.token
.replaceError(with: .failedToRetrieveToken)
.flatMap { [updateUserInformationClient] jwtToken
-> AnyPublisher<Void, WalletNabuSynchronizerServiceError> in
updateUserInformationClient
.updateWalletInfo(jwtToken: jwtToken)
.replaceError(with: .failedToUpdateWalletInfo)
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
}
| 3ebc287bc64b2da0d436360114616145 | 31.5 | 85 | 0.715976 | false | false | false | false |
xu6148152/binea_project_for_ios | refs/heads/master | ListerforAppleWatchiOSandOSX/Swift/ListerKit/CheckBox.swift | mit | 1 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A custom check box used in the lists. It supports designing live in Interface Builder.
*/
import UIKit
@IBDesignable public class CheckBox: UIControl {
// MARK: Properties
@IBInspectable public var isChecked: Bool {
get {
return checkBoxLayer.isChecked
}
set {
checkBoxLayer.isChecked = newValue
}
}
@IBInspectable public var strokeFactor: CGFloat {
set {
checkBoxLayer.strokeFactor = newValue
}
get {
return checkBoxLayer.strokeFactor
}
}
@IBInspectable public var insetFactor: CGFloat {
set {
checkBoxLayer.insetFactor = newValue
}
get {
return checkBoxLayer.insetFactor
}
}
@IBInspectable public var markInsetFactor: CGFloat {
set {
checkBoxLayer.markInsetFactor = newValue
}
get {
return checkBoxLayer.markInsetFactor
}
}
// MARK: Overrides
override public func didMoveToWindow() {
if let window = window {
contentScaleFactor = window.screen.scale
}
}
override public class func layerClass() -> AnyClass {
return CheckBoxLayer.self
}
override public func tintColorDidChange() {
super.tintColorDidChange()
checkBoxLayer.tintColor = tintColor.CGColor
}
// MARK: Convenience
var checkBoxLayer: CheckBoxLayer {
return layer as CheckBoxLayer
}
}
| 2fa53c5fda81b2ed4bdb65c849b9211a | 21.220779 | 90 | 0.582116 | false | false | false | false |
1457792186/JWSwift | refs/heads/dev | ARHome/Pods/ObjectMapper/Sources/DateFormatterTransform.swift | apache-2.0 | 134 | //
// DateFormatterTransform.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-03-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class DateFormatterTransform: TransformType {
public typealias Object = Date
public typealias JSON = String
public let dateFormatter: DateFormatter
public init(dateFormatter: DateFormatter) {
self.dateFormatter = dateFormatter
}
open func transformFromJSON(_ value: Any?) -> Date? {
if let dateString = value as? String {
return dateFormatter.date(from: dateString)
}
return nil
}
open func transformToJSON(_ value: Date?) -> String? {
if let date = value {
return dateFormatter.string(from: date)
}
return nil
}
}
| fbc1a5015df780d8ed632c02ee7e0bc5 | 33.037037 | 81 | 0.737758 | false | false | false | false |
BlessNeo/ios-charts | refs/heads/master | Charts/Classes/Data/BarLineScatterCandleChartDataSet.swift | apache-2.0 | 20 | //
// BarLineScatterCandleChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/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
public class BarLineScatterCandleChartDataSet: ChartDataSet
{
public var highlightColor = UIColor(red: 255.0/255.0, green: 187.0/255.0, blue: 115.0/255.0, alpha: 1.0)
public var highlightLineWidth = CGFloat(1.0)
public var highlightLineDashPhase = CGFloat(0.0)
public var highlightLineDashLengths: [CGFloat]?
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = super.copyWithZone(zone) as! BarLineScatterCandleChartDataSet
copy.highlightColor = highlightColor
copy.highlightLineWidth = highlightLineWidth
copy.highlightLineDashPhase = highlightLineDashPhase
copy.highlightLineDashLengths = highlightLineDashLengths
return copy
}
}
| 5cca6a67c1be807bcd9bf59623755d3e | 30.028571 | 108 | 0.720994 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/SettingsSearchableItems.swift | gpl-2.0 | 1 | //
// SettingsSearchableItems.swift
// Telegram
//
// Created by Mikhail Filimonov on 02.12.2019.
// Copyright © 2019 Telegram. All rights reserved.
//
import Cocoa
import Postbox
import TGUIKit
import SwiftSignalKit
import TelegramCore
import InAppSettings
enum SettingsSearchableItemIcon {
case profile
case proxy
case savedMessages
case calls
case stickers
case notifications
case privacy
case data
case appearance
case language
case watch
case wallet
case passport
case support
case faq
}
extension SettingsSearchableItemIcon {
var thumb: CGImage? {
switch self {
case .profile:
return theme.icons.settingsProfile
case .proxy:
return theme.icons.settingsProxy
case .stickers:
return theme.icons.settingsStickers
case .notifications:
return theme.icons.settingsNotifications
case .privacy:
return theme.icons.settingsSecurity
case .data:
return theme.icons.settingsStorage
case .appearance:
return theme.icons.settingsAppearance
case .language:
return theme.icons.settingsLanguage
case .support:
return theme.icons.settingsAskQuestion
case .faq:
return theme.icons.settingsFaq
default:
return nil
}
}
}
enum SettingsSearchableItemId: Hashable {
case profile(Int32)
case proxy(Int32)
case savedMessages(Int32)
case calls(Int32)
case stickers(Int32)
case notifications(Int32)
case privacy(Int32)
case data(Int32)
case appearance(Int32)
case language(Int32)
case watch(Int32)
case passport(Int32)
case wallet(Int32)
case support(Int32)
case faq(Int32)
private var namespace: Int32 {
switch self {
case .profile:
return 1
case .proxy:
return 2
case .savedMessages:
return 3
case .calls:
return 4
case .stickers:
return 5
case .notifications:
return 6
case .privacy:
return 7
case .data:
return 8
case .appearance:
return 9
case .language:
return 10
case .watch:
return 11
case .passport:
return 12
case .wallet:
return 13
case .support:
return 14
case .faq:
return 15
}
}
private var id: Int32 {
switch self {
case let .profile(id),
let .proxy(id),
let .savedMessages(id),
let .calls(id),
let .stickers(id),
let .notifications(id),
let .privacy(id),
let .data(id),
let .appearance(id),
let .language(id),
let .watch(id),
let .passport(id),
let .wallet(id),
let .support(id),
let .faq(id):
return id
}
}
var index: Int64 {
return (Int64(self.namespace) << 32) | Int64(self.id)
}
init?(index: Int64) {
let namespace = Int32((index >> 32) & 0x7fffffff)
let id = Int32(bitPattern: UInt32(index & 0xffffffff))
switch namespace {
case 1:
self = .profile(id)
case 2:
self = .proxy(id)
case 3:
self = .savedMessages(id)
case 4:
self = .calls(id)
case 5:
self = .stickers(id)
case 6:
self = .notifications(id)
case 7:
self = .privacy(id)
case 8:
self = .data(id)
case 9:
self = .appearance(id)
case 10:
self = .language(id)
case 11:
self = .watch(id)
case 12:
self = .passport(id)
case 13:
self = .wallet(id)
case 14:
self = .support(id)
case 15:
self = .faq(id)
default:
return nil
}
}
}
enum SettingsSearchableItemPresentation {
case push
case modal
case immediate
case dismiss
}
struct SettingsSearchableItem {
let id: SettingsSearchableItemId
let title: String
let alternate: [String]
let icon: SettingsSearchableItemIcon
let breadcrumbs: [String]
let present: (AccountContext, NavigationViewController?, @escaping (SettingsSearchableItemPresentation, ViewController?) -> Void) -> Void
}
func searchSettingsItems(items: [SettingsSearchableItem], query: String) -> [SettingsSearchableItem] {
let queryTokens = stringTokens(query.lowercased())
var result: [SettingsSearchableItem] = []
for item in items {
var string = item.title
if !item.alternate.isEmpty {
for alternate in item.alternate {
let trimmed = alternate.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmed.isEmpty {
string += " \(trimmed)"
}
}
}
if item.breadcrumbs.count > 1 {
string += " \(item.breadcrumbs.suffix(from: 1).joined(separator: " "))"
}
let tokens = stringTokens(string)
if matchStringTokens(tokens, with: queryTokens) {
result.append(item)
}
}
return result
}
private func synonyms(_ string: String?) -> [String] {
if let string = string, !string.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return string.components(separatedBy: "\n")
} else {
return []
}
}
private func stringTokens(_ string: String) -> [ValueBoxKey] {
let nsString = string.folding(options: .diacriticInsensitive, locale: .current).lowercased() as NSString
let flag = UInt(kCFStringTokenizerUnitWord)
let tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, nsString, CFRangeMake(0, nsString.length), flag, CFLocaleCopyCurrent())
var tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)
var tokens: [ValueBoxKey] = []
var addedTokens = Set<ValueBoxKey>()
while tokenType != [] {
let currentTokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer)
if currentTokenRange.location >= 0 && currentTokenRange.length != 0 {
let token = ValueBoxKey(length: currentTokenRange.length * 2)
nsString.getCharacters(token.memory.assumingMemoryBound(to: unichar.self), range: NSMakeRange(currentTokenRange.location, currentTokenRange.length))
if !addedTokens.contains(token) {
tokens.append(token)
addedTokens.insert(token)
}
}
tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)
}
return tokens
}
private func matchStringTokens(_ tokens: [ValueBoxKey], with other: [ValueBoxKey]) -> Bool {
if other.isEmpty {
return false
} else if other.count == 1 {
let otherToken = other[0]
for token in tokens {
if otherToken.isPrefix(to: token) {
return true
}
}
} else {
for otherToken in other {
var found = false
for token in tokens {
if otherToken.isPrefix(to: token) {
found = true
break
}
}
if !found {
return false
}
}
return true
}
return false
}
private func profileSearchableItems(context: AccountContext, canAddAccount: Bool) -> [SettingsSearchableItem] {
let icon: SettingsSearchableItemIcon = .profile
let presentProfileSettings: (AccountContext, @escaping (SettingsSearchableItemPresentation, ViewController?) -> Void, EditSettingsEntryTag?) -> Void = { context, present, itemTag in
EditAccountInfoController(context: context, focusOnItemTag: itemTag, f: { controller in
present(.push, controller)
})
}
var items: [SettingsSearchableItem] = []
items.append(SettingsSearchableItem(id: .profile(0), title: strings().editAccountTitle, alternate: synonyms(strings().settingsSearchSynonymsEditProfileTitle), icon: icon, breadcrumbs: [], present: { context, _, present in
presentProfileSettings(context, present, nil)
}))
items.append(SettingsSearchableItem(id: .profile(1), title: strings().accountSettingsBio, alternate: synonyms(strings().settingsSearchSynonymsEditProfileTitle), icon: icon, breadcrumbs: [strings().editAccountTitle], present: { context, _, present in
presentProfileSettings(context, present, .bio)
}))
items.append(SettingsSearchableItem(id: .profile(2), title: strings().editAccountChangeNumber, alternate: synonyms(strings().settingsSearchSynonymsEditProfilePhoneNumber), icon: icon, breadcrumbs: [strings().editAccountTitle], present: { context, _, present in
present(.push, PhoneNumberIntroController(context))
}))
items.append(SettingsSearchableItem(id: .profile(3), title: strings().editAccountUsername, alternate: synonyms(strings().settingsSearchSynonymsEditProfileUsername), icon: icon, breadcrumbs: [strings().editAccountTitle], present: { context, _, present in
present(.push, UsernameController(context))
}))
if canAddAccount {
items.append(SettingsSearchableItem(id: .profile(4), title: strings().editAccountAddAccount, alternate: synonyms(strings().settingsSearchSynonymsEditProfileAddAccount), icon: icon, breadcrumbs: [strings().editAccountTitle], present: { context, _, present in
let isTestingEnvironment = NSApp.currentEvent?.modifierFlags.contains(.command) == true
context.sharedContext.beginNewAuth(testingEnvironment: isTestingEnvironment)
}))
}
items.append(SettingsSearchableItem(id: .profile(5), title: strings().editAccountLogout, alternate: synonyms(strings().settingsSearchSynonymsEditProfileLogout), icon: icon, breadcrumbs: [strings().editAccountTitle], present: { context, navigationController, present in
showModal(with: LogoutViewController(context: context, f: { controller in
present(.push, controller)
}), for: context.window)
}))
return items
}
private func stickerSearchableItems(context: AccountContext, archivedStickerPacks: [ArchivedStickerPackItem]?) -> [SettingsSearchableItem] {
let icon: SettingsSearchableItemIcon = .stickers
let presentStickerSettings: (AccountContext, (SettingsSearchableItemPresentation, ViewController?) -> Void, InstalledStickerPacksEntryTag?) -> Void = { context, present, itemTag in
present(.push, InstalledStickerPacksController(context, focusOnItemTag: itemTag))
}
var items: [SettingsSearchableItem] = []
items.append(SettingsSearchableItem(id: .stickers(0), title: strings().accountSettingsStickers, alternate: synonyms(strings().settingsSearchSynonymsStickersTitle), icon: icon, breadcrumbs: [], present: { context, _, present in
presentStickerSettings(context, present, nil)
}))
items.append(SettingsSearchableItem(id: .stickers(1), title: strings().stickersSuggestStickers, alternate: synonyms(strings().settingsSearchSynonymsStickersSuggestStickers), icon: icon, breadcrumbs: [strings().accountSettingsStickers], present: { context, _, present in
presentStickerSettings(context, present, .suggestOptions)
}))
items.append(SettingsSearchableItem(id: .stickers(3), title: strings().installedStickersTranding, alternate: synonyms(strings().settingsSearchSynonymsStickersFeaturedPacks), icon: icon, breadcrumbs: [strings().accountSettingsStickers], present: { context, _, present in
present(.push, FeaturedStickerPacksController(context))
}))
items.append(SettingsSearchableItem(id: .stickers(4), title: strings().installedStickersArchived, alternate: synonyms(strings().settingsSearchSynonymsStickersArchivedPacks), icon: icon, breadcrumbs: [strings().accountSettingsStickers], present: { context, _, present in
present(.push, ArchivedStickerPacksController(context, archived: nil, updatedPacks: { _ in }))
}))
return items
}
private func notificationSearchableItems(context: AccountContext, settings: GlobalNotificationSettingsSet) -> [SettingsSearchableItem] {
let icon: SettingsSearchableItemIcon = .notifications
let presentNotificationSettings: (AccountContext, (SettingsSearchableItemPresentation, ViewController?) -> Void, NotificationsAndSoundsEntryTag?) -> Void = { context, present, itemTag in
present(.push, NotificationPreferencesController(context, focusOnItemTag: itemTag))
}
return [
SettingsSearchableItem(id: .notifications(0), title: strings().accountSettingsNotifications, alternate: synonyms(strings().settingsSearchSynonymsNotificationsTitle), icon: icon, breadcrumbs: [], present: { context, _, present in
presentNotificationSettings(context, present, nil)
}),
SettingsSearchableItem(id: .notifications(2), title: strings().notificationSettingsMessagesPreview, alternate: synonyms(strings().settingsSearchSynonymsNotificationsMessageNotificationsPreview), icon: icon, breadcrumbs: [strings().accountSettingsNotifications, strings().notificationSettingsToggleNotificationsHeader], present: { context, _, present in
presentNotificationSettings(context, present, .messagePreviews)
}),
// SettingsSearchableItem(id: .notifications(18), title: strings().notificationSettingsIncludeGroups, alternate: synonyms(strings().settingsSearchSynonymsNotificationsBadgeIncludeMutedPublicGroups), icon: icon, breadcrumbs: [strings().accountSettingsNotifications, strings().notificationSettingsBadgeHeader], present: { context, _, present in
// presentNotificationSettings(context, present, .includePublicGroups)
// }),
SettingsSearchableItem(id: .notifications(19), title: strings().notificationSettingsIncludeChannels, alternate: synonyms(strings().settingsSearchSynonymsNotificationsBadgeIncludeMutedChannels), icon: icon, breadcrumbs: [strings().accountSettingsNotifications, strings().notificationSettingsBadgeHeader], present: { context, _, present in
presentNotificationSettings(context, present, .includeChannels)
}),
SettingsSearchableItem(id: .notifications(20), title: strings().notificationSettingsCountUnreadMessages, alternate: synonyms(strings().settingsSearchSynonymsNotificationsBadgeCountUnreadMessages), icon: icon, breadcrumbs: [strings().accountSettingsNotifications, strings().notificationSettingsBadgeHeader], present: { context, _, present in
presentNotificationSettings(context, present, .unreadCountCategory)
}),
SettingsSearchableItem(id: .notifications(21), title: strings().notificationSettingsContactJoined, alternate: synonyms(strings().settingsSearchSynonymsNotificationsContactJoined), icon: icon, breadcrumbs: [strings().accountSettingsNotifications], present: { context, _, present in
presentNotificationSettings(context, present, .joinedNotifications)
}),
SettingsSearchableItem(id: .notifications(22), title: strings().notificationSettingsResetNotifications, alternate: synonyms(strings().settingsSearchSynonymsNotificationsResetAllNotifications), icon: icon, breadcrumbs: [strings().accountSettingsNotifications], present: { context, _, present in
presentNotificationSettings(context, present, .reset)
})
]
}
private func privacySearchableItems(context: AccountContext, privacySettings: AccountPrivacySettings?) -> [SettingsSearchableItem] {
let icon: SettingsSearchableItemIcon = .privacy
let presentPrivacySettings: (AccountContext, (SettingsSearchableItemPresentation, ViewController?) -> Void, PrivacyAndSecurityEntryTag?) -> Void = { context, present, itemTag in
present(.push, PrivacyAndSecurityViewController(context, initialSettings: nil, focusOnItemTag: itemTag))
}
let presentSelectivePrivacySettings: (AccountContext, SelectivePrivacySettingsKind, @escaping (SettingsSearchableItemPresentation, ViewController?) -> Void) -> Void = { context, kind, present in
let privacySignal: Signal<AccountPrivacySettings, NoError>
if let privacySettings = privacySettings {
privacySignal = .single(privacySettings)
} else {
privacySignal = context.engine.privacy.requestAccountPrivacySettings()
}
let callsSignal: Signal<(VoiceCallSettings, VoipConfiguration)?, NoError>
if case .voiceCalls = kind {
callsSignal = combineLatest(context.sharedContext.accountManager.sharedData(keys: [ApplicationSharedPreferencesKeys.voiceCallSettings]), context.account.postbox.preferencesView(keys: [PreferencesKeys.voipConfiguration]))
|> take(1)
|> map { sharedData, view -> (VoiceCallSettings, VoipConfiguration)? in
let voiceCallSettings: VoiceCallSettings = sharedData.entries[ApplicationSharedPreferencesKeys.voiceCallSettings]?.get(VoiceCallSettings.self) ?? .defaultSettings
let voipConfiguration = view.values[PreferencesKeys.voipConfiguration]?.get(VoipConfiguration.self) ?? .defaultValue
return (voiceCallSettings, voipConfiguration)
}
} else {
callsSignal = .single(nil)
}
let _ = (combineLatest(privacySignal, callsSignal)
|> deliverOnMainQueue).start(next: { info, callSettings in
let current: SelectivePrivacySettings
switch kind {
case .presence:
current = info.presence
case .groupInvitations:
current = info.groupInvitations
case .voiceCalls:
current = info.voiceCalls
case .profilePhoto:
current = info.profilePhoto
case .forwards:
current = info.forwards
case .phoneNumber:
current = info.phoneNumber
case .voiceMessages:
current = info.voiceMessages
}
present(.push, SelectivePrivacySettingsController(context, kind: kind, current: current, callSettings: kind == .voiceCalls ? info.voiceCallsP2P : nil, phoneDiscoveryEnabled: nil, updated: { updated, updatedCallSettings, _ in }))
})
}
let passcodeTitle: String = strings().privacySettingsPasscode
return [
SettingsSearchableItem(id: .privacy(0), title: strings().accountSettingsPrivacyAndSecurity, alternate: synonyms(strings().settingsSearchSynonymsPrivacyTitle), icon: icon, breadcrumbs: [], present: { context, _, present in
presentPrivacySettings(context, present, nil)
}),
SettingsSearchableItem(id: .privacy(1), title: strings().privacySettingsBlockedUsers, alternate: synonyms(strings().settingsSearchSynonymsPrivacyBlockedUsers), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
present(.push, BlockedPeersViewController(context))
}),
SettingsSearchableItem(id: .privacy(2), title: strings().privacySettingsLastSeen, alternate: synonyms(strings().settingsSearchSynonymsPrivacyLastSeen), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
presentSelectivePrivacySettings(context, .presence, present)
}),
SettingsSearchableItem(id: .privacy(3), title: strings().privacySettingsProfilePhoto, alternate: synonyms(strings().settingsSearchSynonymsPrivacyProfilePhoto), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
presentSelectivePrivacySettings(context, .profilePhoto, present)
}),
SettingsSearchableItem(id: .privacy(4), title: strings().privacySettingsForwards, alternate: synonyms(strings().settingsSearchSynonymsPrivacyForwards), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
presentSelectivePrivacySettings(context, .forwards, present)
}),
SettingsSearchableItem(id: .privacy(5), title: strings().privacySettingsVoiceCalls, alternate: synonyms(strings().settingsSearchSynonymsPrivacyCalls), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
presentSelectivePrivacySettings(context, .voiceCalls, present)
}),
SettingsSearchableItem(id: .privacy(6), title: strings().privacySettingsGroups, alternate: synonyms(strings().settingsSearchSynonymsPrivacyGroupsAndChannels), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
presentSelectivePrivacySettings(context, .groupInvitations, present)
}),
SettingsSearchableItem(id: .privacy(7), title: passcodeTitle, alternate: [], icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
present(.push, PasscodeSettingsViewController(context))
}),
SettingsSearchableItem(id: .privacy(8), title: strings().privacySettingsTwoStepVerification, alternate: synonyms(strings().settingsSearchSynonymsPrivacyTwoStepAuth), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, navigation, present in
present(.push, twoStepVerificationUnlockController(context: context, mode: .access(nil), presentController: { controller, root, animated in
guard let navigation = navigation else {return}
if root {
navigation.removeUntil(PrivacyAndSecurityViewController.self)
}
if !animated {
navigation.stackInsert(controller, at: navigation.stackCount)
} else {
navigation.push(controller)
}
}))
}),
SettingsSearchableItem(id: .privacy(9), title: strings().privacySettingsActiveSessions, alternate: synonyms(strings().settingsSearchSynonymsPrivacyAuthSessions), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
present(.push, RecentSessionsController(context))
}),
SettingsSearchableItem(id: .privacy(10), title: strings().privacySettingsDeleteAccountHeader, alternate: synonyms(strings().settingsSearchSynonymsPrivacyDeleteAccountIfAwayFor), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
presentPrivacySettings(context, present, .accountTimeout)
}),
SettingsSearchableItem(id: .privacy(14), title: strings().suggestFrequentContacts, alternate: synonyms(strings().settingsSearchSynonymsPrivacyDataTopPeers), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
presentPrivacySettings(context, present, .topPeers)
}),
SettingsSearchableItem(id: .privacy(15), title: strings().privacyAndSecurityClearCloudDrafts, alternate: synonyms(strings().settingsSearchSynonymsPrivacyDataDeleteDrafts), icon: icon, breadcrumbs: [strings().accountSettingsPrivacyAndSecurity], present: { context, _, present in
presentPrivacySettings(context, present, .cloudDraft)
})
]
}
private func dataSearchableItems(context: AccountContext) -> [SettingsSearchableItem] {
let icon: SettingsSearchableItemIcon = .data
let presentDataSettings: (AccountContext, (SettingsSearchableItemPresentation, ViewController?) -> Void, DataAndStorageEntryTag?) -> Void = { context, present, itemTag in
present(.push, DataAndStorageViewController(context, focusOnItemTag: itemTag))
}
return [
SettingsSearchableItem(id: .data(0), title: strings().accountSettingsDataAndStorage, alternate: synonyms(strings().settingsSearchSynonymsDataTitle), icon: icon, breadcrumbs: [], present: { context, _, present in
presentDataSettings(context, present, nil)
}),
SettingsSearchableItem(id: .data(1), title: strings().dataAndStorageStorageUsage, alternate: synonyms(strings().settingsSearchSynonymsDataStorageTitle), icon: icon, breadcrumbs: [strings().accountSettingsDataAndStorage], present: { context, _, present in
present(.push, StorageUsageController(context))
}),
SettingsSearchableItem(id: .data(2), title: strings().storageUsageKeepMedia, alternate: synonyms(strings().settingsSearchSynonymsDataStorageKeepMedia), icon: icon, breadcrumbs: [strings().accountSettingsDataAndStorage, strings().dataAndStorageStorageUsage], present: { context, _, present in
present(.push, StorageUsageController(context))
}),
SettingsSearchableItem(id: .data(3), title: strings().logoutOptionsClearCacheTitle, alternate: synonyms(strings().settingsSearchSynonymsDataStorageClearCache), icon: icon, breadcrumbs: [strings().accountSettingsDataAndStorage, strings().dataAndStorageStorageUsage], present: { context, _, present in
present(.push, StorageUsageController(context))
}),
SettingsSearchableItem(id: .data(4), title: strings().dataAndStorageNetworkUsage, alternate: synonyms(strings().settingsSearchSynonymsDataNetworkUsage), icon: icon, breadcrumbs: [strings().accountSettingsDataAndStorage], present: { context, _, present in
present(.push, networkUsageStatsController(context: context))
}),
SettingsSearchableItem(id: .data(7), title: strings().dataAndStorageAutomaticDownloadReset, alternate: synonyms(strings().settingsSearchSynonymsDataAutoDownloadReset), icon: icon, breadcrumbs: [strings().accountSettingsDataAndStorage], present: { context, _, present in
presentDataSettings(context, present, .automaticDownloadReset)
}),
SettingsSearchableItem(id: .data(8), title: strings().dataAndStorageAutoplayGIFs, alternate: synonyms(strings().settingsSearchSynonymsDataAutoplayGifs), icon: icon, breadcrumbs: [strings().accountSettingsDataAndStorage, strings().dataAndStorageAutoplayHeader], present: { context, _, present in
presentDataSettings(context, present, .autoplayGifs)
}),
SettingsSearchableItem(id: .data(9), title: strings().dataAndStorageAutoplayVideos, alternate: synonyms(strings().settingsSearchSynonymsDataAutoplayVideos), icon: icon, breadcrumbs: [strings().accountSettingsDataAndStorage, strings().dataAndStorageAutoplayHeader], present: { context, _, present in
presentDataSettings(context, present, .autoplayVideos)
})
]
}
private func proxySearchableItems(context: AccountContext, servers: [ProxyServerSettings]) -> [SettingsSearchableItem] {
let icon: SettingsSearchableItemIcon = .proxy
let presentProxySettings: (AccountContext, @escaping(SettingsSearchableItemPresentation, ViewController?) -> Void) -> Void = { context, present in
let controller = proxyListController(accountManager: context.sharedContext.accountManager, network: context.account.network, share: { servers in
var message: String = ""
for server in servers {
message += server.link + "\n\n"
}
message = message.trimmed
showModal(with: ShareModalController(ShareLinkObject(context, link: message)), for: context.window)
}, pushController: { controller in
present(.push, controller)
})
present(.push, controller)
}
var items: [SettingsSearchableItem] = []
items.append(SettingsSearchableItem(id: .proxy(0), title: strings().accountSettingsProxy, alternate: synonyms(strings().settingsSearchSynonymsProxyTitle), icon: icon, breadcrumbs: [], present: { context, _, present in
presentProxySettings(context, present)
}))
items.append(SettingsSearchableItem(id: .proxy(1), title: strings().proxySettingsAddProxy, alternate: synonyms(strings().settingsSearchSynonymsProxyAddProxy), icon: icon, breadcrumbs: [strings().accountSettingsProxy], present: { context, _, present in
presentProxySettings(context, present)
}))
var hasSocksServers = false
for server in servers {
if case .socks5 = server.connection {
hasSocksServers = true
break
}
}
if hasSocksServers {
items.append(SettingsSearchableItem(id: .proxy(2), title: strings().proxySettingsUseForCalls, alternate: synonyms(strings().settingsSearchSynonymsProxyUseForCalls), icon: icon, breadcrumbs: [strings().accountSettingsProxy], present: { context, _, present in
presentProxySettings(context, present)
}))
}
return items
}
private func appearanceSearchableItems(context: AccountContext) -> [SettingsSearchableItem] {
let icon: SettingsSearchableItemIcon = .appearance
let presentAppearanceSettings: (AccountContext, (SettingsSearchableItemPresentation, ViewController?) -> Void, ThemeSettingsEntryTag?) -> Void = { context, present, itemTag in
present(.push, AppAppearanceViewController(context: context, focusOnItemTag: itemTag))
}
return [
SettingsSearchableItem(id: .appearance(0), title: strings().accountSettingsTheme, alternate: synonyms(strings().settingsSearchSynonymsAppearanceTitle), icon: icon, breadcrumbs: [], present: { context, _, present in
presentAppearanceSettings(context, present, nil)
}),
SettingsSearchableItem(id: .appearance(1), title: strings().appearanceSettingsTextSizeHeader, alternate: synonyms(strings().settingsSearchSynonymsAppearanceTextSize), icon: icon, breadcrumbs: [strings().accountSettingsTheme], present: { context, _, present in
presentAppearanceSettings(context, present, .fontSize)
}),
SettingsSearchableItem(id: .appearance(2), title: strings().generalSettingsChatBackground, alternate: synonyms(strings().settingsSearchSynonymsAppearanceChatBackground), icon: icon, breadcrumbs: [strings().accountSettingsTheme], present: { context, _, present in
showModal(with: ChatWallpaperModalController(context), for: context.window)
}),
SettingsSearchableItem(id: .appearance(5), title: strings().appearanceSettingsAutoNight, alternate: synonyms(strings().settingsSearchSynonymsAppearanceAutoNightTheme), icon: icon, breadcrumbs: [strings().accountSettingsTheme], present: { context, _, present in
present(.push, AutoNightSettingsController(context: context))
}),
SettingsSearchableItem(id: .appearance(6), title: strings().appearanceSettingsColorThemeHeader, alternate: synonyms(strings().settingsSearchSynonymsAppearanceColorTheme), icon: icon, breadcrumbs: [strings().accountSettingsTheme], present: { context, _, present in
presentAppearanceSettings(context, present, .accentColor)
}),
SettingsSearchableItem(id: .appearance(6), title: strings().appearanceSettingsChatViewHeader, alternate: synonyms(strings().settingsSearchSynonymsAppearanceChatMode), icon: icon, breadcrumbs: [strings().accountSettingsTheme], present: { context, _, present in
presentAppearanceSettings(context, present, .chatMode)
}),
]
}
private func languageSearchableItems(context: AccountContext, localizations: [LocalizationInfo]) -> [SettingsSearchableItem] {
let icon: SettingsSearchableItemIcon = .language
let applyLocalization: (AccountContext, @escaping (SettingsSearchableItemPresentation, ViewController?) -> Void, String) -> Void = { context, present, languageCode in
_ = showModalProgress(signal: context.engine.localization.downloadAndApplyLocalization(accountManager: context.sharedContext.accountManager, languageCode: languageCode), for: context.window).start()
}
var items: [SettingsSearchableItem] = []
items.append(SettingsSearchableItem(id: .language(0), title: strings().accountSettingsLanguage, alternate: synonyms(strings().settingsSearchSynonymsAppLanguage), icon: icon, breadcrumbs: [], present: { context, _, present in
present(.push, LanguageViewController(context))
}))
var index: Int32 = 1
for localization in localizations {
items.append(SettingsSearchableItem(id: .language(index), title: localization.localizedTitle, alternate: [localization.title], icon: icon, breadcrumbs: [strings().accountSettingsLanguage], present: { context, _, present in
applyLocalization(context, present, localization.languageCode)
}))
index += 1
}
return items
}
func settingsSearchableItems(context: AccountContext, archivedStickerPacks: Signal<[ArchivedStickerPackItem]?, NoError>, privacySettings: Signal<AccountPrivacySettings?, NoError>) -> Signal<[SettingsSearchableItem], NoError> {
let canAddAccount = activeAccountsAndPeers(context: context)
|> take(1)
|> map { accountsAndPeers -> Bool in
return accountsAndPeers.1.count + 1 < maximumNumberOfAccounts
}
let notificationSettings = context.account.postbox.preferencesView(keys: [PreferencesKeys.globalNotifications])
|> take(1)
|> map { view -> GlobalNotificationSettingsSet in
let viewSettings: GlobalNotificationSettingsSet
if let settings = view.values[PreferencesKeys.globalNotifications]?.get(GlobalNotificationSettings.self) {
viewSettings = settings.effective
} else {
viewSettings = GlobalNotificationSettingsSet.defaultSettings
}
return viewSettings
}
let archivedStickerPacks = archivedStickerPacks
|> take(1)
let privacySettings = privacySettings
|> take(1)
let proxyServers = context.sharedContext.accountManager.sharedData(keys: [SharedDataKeys.proxySettings])
|> map { sharedData -> ProxySettings in
if let value = sharedData.entries[SharedDataKeys.proxySettings]?.get(ProxySettings.self) {
return value
} else {
return ProxySettings.defaultSettings
}
}
|> map { settings -> [ProxyServerSettings] in
return settings.servers
}
let localizationPreferencesKey: PostboxViewKey = .preferences(keys: Set([PreferencesKeys.localizationListState]))
let localizations = combineLatest(context.account.postbox.combinedView(keys: [localizationPreferencesKey]), context.sharedContext.accountManager.sharedData(keys: [SharedDataKeys.localizationSettings]))
|> map { view, sharedData -> [LocalizationInfo] in
if let localizationListState = (view.views[localizationPreferencesKey] as? PreferencesView)?.values[PreferencesKeys.localizationListState]?.get(LocalizationListState.self), !localizationListState.availableOfficialLocalizations.isEmpty {
var existingIds = Set<String>()
let availableSavedLocalizations = localizationListState.availableSavedLocalizations.filter({ info in !localizationListState.availableOfficialLocalizations.contains(where: { $0.languageCode == info.languageCode }) })
var activeLanguageCode: String?
if let localizationSettings = sharedData.entries[SharedDataKeys.localizationSettings]?.get(LocalizationSettings.self) {
activeLanguageCode = localizationSettings.primaryComponent.languageCode
}
var localizationItems: [LocalizationInfo] = []
if !availableSavedLocalizations.isEmpty {
for info in availableSavedLocalizations {
if existingIds.contains(info.languageCode) || info.languageCode == activeLanguageCode {
continue
}
existingIds.insert(info.languageCode)
localizationItems.append(info)
}
}
for info in localizationListState.availableOfficialLocalizations {
if existingIds.contains(info.languageCode) || info.languageCode == activeLanguageCode {
continue
}
existingIds.insert(info.languageCode)
localizationItems.append(info)
}
return localizationItems
} else {
return []
}
}
return combineLatest(canAddAccount, localizations, notificationSettings, archivedStickerPacks, proxyServers, privacySettings)
|> map { canAddAccount, localizations, notificationSettings, archivedStickerPacks, proxyServers, privacySettings in
var allItems: [SettingsSearchableItem] = []
let profileItems = profileSearchableItems(context: context, canAddAccount: canAddAccount)
allItems.append(contentsOf: profileItems)
let stickerItems = stickerSearchableItems(context: context, archivedStickerPacks: archivedStickerPacks)
allItems.append(contentsOf: stickerItems)
let notificationItems = notificationSearchableItems(context: context, settings: notificationSettings)
allItems.append(contentsOf: notificationItems)
let privacyItems = privacySearchableItems(context: context, privacySettings: privacySettings)
allItems.append(contentsOf: privacyItems)
let dataItems = dataSearchableItems(context: context)
allItems.append(contentsOf: dataItems)
let proxyItems = proxySearchableItems(context: context, servers: proxyServers)
allItems.append(contentsOf: proxyItems)
let appearanceItems = appearanceSearchableItems(context: context)
allItems.append(contentsOf: appearanceItems)
let languageItems = languageSearchableItems(context: context, localizations: localizations)
allItems.append(contentsOf: languageItems)
let support = SettingsSearchableItem(id: .support(0), title: strings().accountSettingsAskQuestion, alternate: synonyms(strings().settingsSearchSynonymsSupport), icon: .support, breadcrumbs: [], present: { context, _, present in
confirm(for: context.window, information: strings().accountConfirmAskQuestion, thridTitle: strings().accountConfirmGoToFaq, successHandler: { result in
switch result {
case .basic:
_ = showModalProgress(signal: context.engine.peers.supportPeerId(), for: context.window).start(next: { peerId in
if let peerId = peerId {
present(.push, ChatController(context: context, chatLocation: .peer(peerId)))
}
})
case .thrid:
let _ = (cachedFaqInstantPage(context: context) |> deliverOnMainQueue).start(next: { resolvedUrl in
execute(inapp: resolvedUrl)
})
}
})
})
allItems.append(support)
let faq = SettingsSearchableItem(id: .faq(0), title: strings().accountSettingsFAQ, alternate: synonyms(strings().settingsSearchSynonymsFAQ), icon: .faq, breadcrumbs: [], present: { context, navigationController, present in
let _ = (cachedFaqInstantPage(context: context) |> deliverOnMainQueue).start(next: { resolvedUrl in
execute(inapp: resolvedUrl)
})
})
allItems.append(faq)
return allItems
}
}
| e184ac0b3cd4df4a32d8a78e21c5e59c | 51.963303 | 360 | 0.675856 | false | false | false | false |
davejlong/ResponseDetective | refs/heads/develop | ResponseDetective Tests/Source Files/TestImageGenerator.swift | mit | 1 | //
// TestImageGenerator.swift
//
// Copyright (c) 2015 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
private typealias OSImage = UIImage
#else
import AppKit
private typealias OSImage = NSImage
#endif
/// Generates test images.
internal struct TestImageGenerator {
/// The image MIME type.
internal enum TestImageType {
case PNG
}
/// Platform-agnostic image size type.
internal typealias TestImageSize = (width: Int, height: Int)
/// Generates image data.
///
/// - parameter type: The type of the image.
/// - parameter size: The image size.
///
/// - returns: Image data.
internal static func generateImageData(type type: TestImageType, size: TestImageSize) -> NSData {
#if os(iOS)
switch type {
case .PNG:
return UIImagePNGRepresentation(generateImage(size: size))!
}
#else
return Optional(generateImage(size: size)).flatMap({
$0.TIFFRepresentation
}).flatMap({
NSBitmapImageRep(data: $0)
}).flatMap({
switch type {
case .PNG:
return $0.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [
NSImageCompressionFactor: 1
])
}
})!
#endif
}
/// Creates an image with a black background.
///
/// - parameter size: The size of the image.
///
/// - returns: The generated image.
private static func generateImage(size size: TestImageSize) -> OSImage {
#if os(iOS)
let bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(bounds.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
CGContextFillRect(context, bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
#else
let bounds = NSRect(x: 0, y: 0, width: size.width, height: size.height)
let image = NSImage(size: bounds.size)
image.lockFocus()
NSColor.blackColor().drawSwatchInRect(bounds)
image.unlockFocus()
return image
#endif
}
}
| 035bbc94165b7aae4e8996310513d4f5 | 24.469136 | 98 | 0.697528 | false | true | false | false |
EurekaCommunity/ColorPickerRow | refs/heads/master | Pods/Eureka/Source/Core/BaseRow.swift | mit | 1 | // BaseRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
open class BaseRow: BaseRowType {
var callbackOnChange: (() -> Void)?
var callbackCellUpdate: (() -> Void)?
var callbackCellSetup: Any?
var callbackCellOnSelection: (() -> Void)?
var callbackOnExpandInlineRow: Any?
var callbackOnCollapseInlineRow: Any?
var callbackOnCellHighlightChanged: (() -> Void)?
var callbackOnRowValidationChanged: (() -> Void)?
var _inlineRow: BaseRow?
var _cachedOptionsData: Any?
public var validationOptions: ValidationOptions = .validatesOnBlur
// validation state
public internal(set) var validationErrors = [ValidationError]() {
didSet {
guard validationErrors != oldValue else { return }
RowDefaults.onRowValidationChanged["\(type(of: self))"]?(baseCell, self)
callbackOnRowValidationChanged?()
updateCell()
}
}
public internal(set) var wasBlurred = false
public internal(set) var wasChanged = false
public var isValid: Bool { return validationErrors.isEmpty }
public var isHighlighted: Bool = false
/// The title will be displayed in the textLabel of the row.
public var title: String?
/// Parameter used when creating the cell for this row.
public var cellStyle = UITableViewCell.CellStyle.value1
/// String that uniquely identifies a row. Must be unique among rows and sections.
public var tag: String?
/// The untyped cell associated to this row.
public var baseCell: BaseCell! { return nil }
/// The untyped value of this row.
public var baseValue: Any? {
set {}
get { return nil }
}
public func validate(quietly: Bool = false) -> [ValidationError] {
return []
}
public static var estimatedRowHeight: CGFloat = 44.0
/// Condition that determines if the row should be disabled or not.
public var disabled: Condition? {
willSet { removeFromDisabledRowObservers() }
didSet { addToDisabledRowObservers() }
}
/// Condition that determines if the row should be hidden or not.
public var hidden: Condition? {
willSet { removeFromHiddenRowObservers() }
didSet { addToHiddenRowObservers() }
}
/// Returns if this row is currently disabled or not
public var isDisabled: Bool { return disabledCache }
/// Returns if this row is currently hidden or not
public var isHidden: Bool { return hiddenCache }
/// The section to which this row belongs.
open weak var section: Section?
public lazy var trailingSwipe = {[unowned self] in SwipeConfiguration(self)}()
//needs the accessor because if marked directly this throws "Stored properties cannot be marked potentially unavailable with '@available'"
private lazy var _leadingSwipe = {[unowned self] in SwipeConfiguration(self)}()
@available(iOS 11,*)
public var leadingSwipe: SwipeConfiguration{
get { return self._leadingSwipe }
set { self._leadingSwipe = newValue }
}
public required init(tag: String? = nil) {
self.tag = tag
}
/**
Method that reloads the cell
*/
open func updateCell() {}
/**
Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell.
*/
open func didSelect() {}
open func prepare(for segue: UIStoryboardSegue) {}
/**
Helps to pick destination part of the cell after scrolling
*/
open var destinationScrollPosition: UITableView.ScrollPosition? = UITableView.ScrollPosition.bottom
/**
Returns the IndexPath where this row is in the current form.
*/
public final var indexPath: IndexPath? {
guard let sectionIndex = section?.index, let rowIndex = section?.firstIndex(of: self) else { return nil }
return IndexPath(row: rowIndex, section: sectionIndex)
}
var hiddenCache = false
var disabledCache = false {
willSet {
if newValue && !disabledCache {
baseCell.cellResignFirstResponder()
}
}
}
}
extension BaseRow {
// Reset validation
public func cleanValidationErrors(){
validationErrors = []
}
}
extension BaseRow {
/**
Evaluates if the row should be hidden or not and updates the form accordingly
*/
public final func evaluateHidden() {
guard let h = hidden, let form = section?.form else { return }
switch h {
case .function(_, let callback):
hiddenCache = callback(form)
case .predicate(let predicate):
hiddenCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
if hiddenCache {
section?.hide(row: self)
} else {
section?.show(row: self)
}
}
/**
Evaluates if the row should be disabled or not and updates it accordingly
*/
public final func evaluateDisabled() {
guard let d = disabled, let form = section?.form else { return }
switch d {
case .function(_, let callback):
disabledCache = callback(form)
case .predicate(let predicate):
disabledCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
updateCell()
}
final func wasAddedTo(section: Section) {
self.section = section
if let t = tag {
assert(section.form?.rowsByTag[t] == nil, "Duplicate tag \(t)")
self.section?.form?.rowsByTag[t] = self
self.section?.form?.tagToValues[t] = baseValue != nil ? baseValue! : NSNull()
}
addToRowObservers()
evaluateHidden()
evaluateDisabled()
}
final func addToHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.addRowObservers(to: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func addToDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.addRowObservers(to: self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func addToRowObservers() {
addToHiddenRowObservers()
addToDisabledRowObservers()
}
final func willBeRemovedFromForm() {
(self as? BaseInlineRowType)?.collapseInlineRow()
if let t = tag {
section?.form?.rowsByTag[t] = nil
section?.form?.tagToValues[t] = nil
}
removeFromRowObservers()
}
final func willBeRemovedFromSection() {
willBeRemovedFromForm()
section = nil
}
final func removeFromHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.removeRowObservers(from: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func removeFromDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.removeRowObservers(from: self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func removeFromRowObservers() {
removeFromHiddenRowObservers()
removeFromDisabledRowObservers()
}
}
extension BaseRow: Equatable, Hidable, Disableable {}
extension BaseRow {
public func reload(with rowAnimation: UITableView.RowAnimation = .none) {
guard let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView, let indexPath = indexPath else { return }
tableView.reloadRows(at: [indexPath], with: rowAnimation)
}
public func deselect(animated: Bool = true) {
guard let indexPath = indexPath,
let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.deselectRow(at: indexPath, animated: animated)
}
public func select(animated: Bool = false, scrollPosition: UITableView.ScrollPosition = .none) {
guard let indexPath = indexPath,
let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
}
public func == (lhs: BaseRow, rhs: BaseRow) -> Bool {
return lhs === rhs
}
| cf85f4907158754773255ab7bbcd09af | 34.216216 | 177 | 0.655794 | false | false | false | false |
bnickel/bite-swift | refs/heads/master | Bite/Bite.swift | mit | 1 | //
// Extensions.swift
// Bite
//
// Created by Brian Nickel on 6/10/14.
// Copyright (c) 2014 Brian Nickel. All rights reserved.
//
public struct Bite<T where T:SequenceType> {
let source:T
public init(_ source:T) {
self.source = source
}
}
extension Bite : SequenceType {
public func generate() -> T.Generator {
return source.generate()
}
}
extension Bite {
public func take(count: Int) -> Bite<TakeSequence<T>> {
return Bite<TakeSequence<T>>(TakeSequence(source, count:count))
}
public func skip(count: Int) -> Bite<SkipSequence<T>> {
return Bite<SkipSequence<T>>(SkipSequence(source, count:count))
}
public func filter(includeElement: T.Generator.Element -> Bool) -> Bite<FilterSequence<T>> {
return Bite<FilterSequence<T>>(FilterSequence(source, includeElement))
}
public func map<U>(transform: T.Generator.Element -> U) -> Bite<MapSequence<T, U>> {
return Bite<MapSequence<T, U>>(MapSequence(source, transform))
}
public func takeWhile(includeElement: T.Generator.Element -> Bool) -> Bite<TakeWhileSequence<T>> {
return Bite<TakeWhileSequence<T>>(TakeWhileSequence(source, includeElement))
}
public func takeUntil(excludeElement: T.Generator.Element -> Bool) -> Bite<TakeWhileSequence<T>> {
return Bite<TakeWhileSequence<T>>(TakeWhileSequence(source, { !excludeElement($0) }))
}
public func and<U:SequenceType where T.Generator.Element == U.Generator.Element>(sequence:U) -> Bite<AndSequence<T, U>> {
return Bite<AndSequence<T, U>>(AndSequence(source, sequence))
}
}
extension Bite {
public var count: Int {
var count = 0
for element in source {
count++
}
return count
}
public var firstElement: T.Generator.Element? {
for element in source {
return element
}
return nil
}
public var lastElement: T.Generator.Element? {
var lastElement:T.Generator.Element? = nil
for element in source {
lastElement = element
}
return lastElement
}
public func array() -> Array<T.Generator.Element> {
return Array(source)
}
public func dictionary<KeyType : Hashable, ValueType>(pairs: T.Generator.Element -> (KeyType, ValueType)) -> Dictionary<KeyType, ValueType> {
var dictionary = Dictionary<KeyType, ValueType>()
for element in source {
let (key, value) = pairs(element)
dictionary[key] = value
}
return dictionary
}
public func groupBy<KeyType : Hashable>(transform: T.Generator.Element -> KeyType) -> Bite<Dictionary<KeyType, Array<T.Generator.Element>>> {
var dictionary = Dictionary<KeyType, Array<T.Generator.Element>>()
for element in source {
let key = transform(element)
let foundArray = dictionary[key]
var array = foundArray ?? Array<T.Generator.Element>()
array += [element]
dictionary[key] = array
}
return Bite<Dictionary<KeyType, Array<T.Generator.Element>>>(dictionary)
}
public func any(test: T.Generator.Element -> Bool) -> Bool {
for element in source {
if test(element) {
return true
}
}
return false
}
public func all(test: T.Generator.Element -> Bool) -> Bool {
for element in source {
if !test(element) {
return false
}
}
return true
}
public func foldLeft<U>(inital: U, combine: (U, T.Generator.Element) -> U) -> U {
return Bite.foldGeneratorLeft(source.generate(), initial: inital, combine)
}
public func reduceLeft(combine: (T.Generator.Element, T.Generator.Element) -> T.Generator.Element) -> T.Generator.Element? {
var generator = source.generate()
if let initial = generator.next() {
return Bite.foldGeneratorLeft(generator, initial: initial, combine)
} else {
return nil
}
}
public func foldRight<U>(inital: U, combine: (T.Generator.Element, U) -> U) -> U {
let reversed = Bite<Array<T.Generator.Element>>(array().reverse())
return reversed.foldLeft(inital, { combine($1, $0) })
}
public func reduceRight(combine: (T.Generator.Element, T.Generator.Element) -> T.Generator.Element) -> T.Generator.Element? {
let reversed = Bite<Array<T.Generator.Element>>(array().reverse())
return reversed.reduceLeft({ combine($1, $0) })
}
public static func foldGeneratorLeft<G : GeneratorType, U>(var generator: G, initial: U, combine: (U, G.Element) -> U) -> U {
var value = initial
while let element = generator.next() {
value = combine(value, element)
}
return value
}
}
| 364e62170bcf1127ce4289a7986c386f | 31.493506 | 145 | 0.598921 | false | false | false | false |
ShunzhiTang/SinaDateTest | refs/heads/master | SinaDateTest/SinaDateTest/NSDate+Extension.swift | mit | 2 | //
// NSDate+Extension.swift
// Copyright © 2015年 Tsz. All rights reserved.
//
import Foundation
extension NSDate{
class func sinaDate(string: String) -> NSDate?{
//转换日期
let df = NSDateFormatter()
df.locale = NSLocale(localeIdentifier: "en")
df.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
//转换
return df.dateFromString(string)
}
//根据判断 获取不同时间段的称呼
var dateDesctiption: String {
//1、使用日历类取出当前的日期
let calendar = NSCalendar.currentCalendar()
//判断
if calendar.isDateInToday(self){
//把获取的日期和现在的系统时进行比较,判断时间差
let dateTime = Int(NSDate().timeIntervalSinceDate(self))
if dateTime < 60 {
return "🆔刚刚"
}
if dateTime < 3600 {
return "🆔\(dateTime / 60)分钟前"
}
return "🆔\(dateTime / 3600)小时前"
}
//日格式字符串
var fmtString = "HH:mm"
if calendar.isDateInYesterday(self){
fmtString = "昨天" + fmtString
}else{
fmtString = "MM-dd" + fmtString
let coms = calendar.components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
if coms.year > 0{
fmtString = "yyyy-" + fmtString
}
}
let df = NSDateFormatter()
df.locale = NSLocale(localeIdentifier: "en")
df.dateFormat = fmtString
return df.stringFromDate(self)
}
} | 419bb203d15a123c967e603479d8e77e | 25.079365 | 138 | 0.50609 | false | false | false | false |
Decybel07/AsyncTimer | refs/heads/master | Source/AsyncTimer.swift | mit | 1 | //
// AsyncTimer.swift
// AsyncTimer
//
// Created by Adrian Bobrowski on 21.06.2017.
// Copyright © 2017 Adrian Bobrowski (Decybel07), [email protected]. All rights reserved.
//
import Foundation
/// Class AsyncTimer.
open class AsyncTimer {
private let queue: DispatchQueue
private let interval: DispatchTimeInterval
private let counter: Counter
private let block: (Int) -> Void
private let completion: () -> Void
private var task: Task?
/// A Boolean value that determines whether the timer is paused.
public var isPaused: Bool {
return self.task?.isSuspended ?? false
}
/// A Boolean value that determines whether the timer is stopped.
public var isStopped: Bool {
return self.task == nil
}
/// A Boolean value that determines whether the timer is running.
public var isRunning: Bool {
return !(self.isStopped || self.isPaused)
}
/// An Integer value that determines the number of remaining iterations.
/// If the timer is infinity or stopped then return nil
public var value: Int? {
if let counter = self.task?.counter, case let .down(value) = counter {
return value
}
return nil
}
/**
Initialize a new AsyncTimer. A timer waits until a certain time **interval** has elapsed and then call the **block** clause.
- parameter queue: The queue on which the timer will start.
- parameter interval: The time interval between calls to the **block** clause.
- parameter repeats: If true, the timer will infinity work until stop method called. If false, the timer will be stop after first iteration.
- parameter block: A closure to be executed when the time **interval** expires. This block has no return value and has no take any argument.
- returns: A AsyncTimer object.
*/
public convenience init(
queue: DispatchQueue = .main,
interval: DispatchTimeInterval,
repeats: Bool = false,
block: @escaping () -> Void = {}
) {
if repeats {
self.init(queue: queue, interval: interval, counter: .infinity, block: { _ in block() })
} else {
self.init(queue: queue, interval: interval, counter: .down(1), completion: block)
}
}
/**
Initialize a new AsyncTimer. A timer waits until a certain time **interval** has elapsed and then call the **block** clause.
- parameter queue: The queue on which the timer will start.
- parameter interval: The time interval between calls to the **block** clause.
- parameter times: The number of iterations.
- parameter block: A closure to be executed after changing the number of remaining iterations. This block has no return value and takes single Int argument that indicates number of remaining iterations.
- parameter completion: A closure to be executed when the timer finishes work. This block has no return value and has no take any argument.
- returns: A AsyncTimer object.
*/
public convenience init(
queue: DispatchQueue = .main,
interval: DispatchTimeInterval,
times: Int,
block: @escaping (Int) -> Void = { _ in },
completion: @escaping () -> Void = {}
) {
self.init(queue: queue, interval: interval, counter: .down(times), block: block, completion: completion)
}
private init(
queue: DispatchQueue,
interval: DispatchTimeInterval,
counter: Counter,
block: @escaping (Int) -> Void = { _ in },
completion: @escaping () -> Void = {}
) {
self.queue = queue
self.counter = counter
self.interval = interval
self.block = block
self.completion = completion
}
/// Destroy the timer
deinit {
self.stop()
}
/// Start the timer
open func start() {
guard self.task == nil else {
return
}
self.startTask(Task(self.counter))
}
/// Pause the timer
open func pause() {
self.task?.isSuspended = true
}
/// Resume the timer
open func resume() {
guard let task = self.task, task.isSuspended else {
return
}
self.startTask(Task(task))
}
/// Stop the timer
open func stop() {
self.pause()
self.task = nil
}
/// Restart the timer
open func restart() {
self.stop()
self.start()
}
private func startTask(_ task: Task) {
self.task = task
self.update(task.getStartTime(), with: task)
}
private func update(_ time: DispatchTime, with task: Task) {
if task.isSuspended {
return
}
if task.isCompleted {
self.stop()
self.block(0)
self.completion()
return
}
task.startedTime = time
let nextTime = time + self.interval
self.queue.asyncAfter(deadline: nextTime) { [weak self] in
self?.update(nextTime, with: task.next)
}
self.block(task.counter.value)
}
}
| 5ecc3d0145ad767cf3d9c25cc07342a2 | 30.036364 | 207 | 0.61199 | false | false | false | false |
revealapp/Revert | refs/heads/master | Shared/Sources/AutoLayoutGuidesViewController.swift | bsd-3-clause | 1 | //
// Copyright © 2017 Itty Bitty Apps. All rights reserved.
import Foundation
@available(iOS 9.0, tvOS 9.0, *)
final class AutoLayoutGuidesViewController: RevertViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Manually creating constraints and guides as they're unavailable in IB
let layoutMarginsGuide = self.view.layoutMarginsGuide
let readableContentGuide = self.view.readableContentGuide
let customLayoutGuide = AutoLayoutGuidesViewController.customLayoutGuide(addedTo: self.view)
let sideMargin: CGFloat
#if os(iOS)
sideMargin = 0
#else
sideMargin = 60
#endif
NSLayoutConstraint.activate([
self.topLeftView.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: sideMargin),
self.topRightView.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -sideMargin),
self.bottomLeftView.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: sideMargin),
self.bottomRightView.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -sideMargin),
self.topLabel.leadingAnchor.constraint(equalTo: readableContentGuide.leadingAnchor),
self.topLabel.trailingAnchor.constraint(equalTo: readableContentGuide.trailingAnchor),
self.topLabel.bottomAnchor.constraint(equalTo: customLayoutGuide.topAnchor),
self.bottomLabel.leadingAnchor.constraint(equalTo: readableContentGuide.leadingAnchor),
self.bottomLabel.trailingAnchor.constraint(equalTo: readableContentGuide.trailingAnchor),
self.bottomLabel.topAnchor.constraint(equalTo: customLayoutGuide.bottomAnchor)
])
// Manually embedding a view controller so that its top/bottom layout guides are actual UILayoutGuide objects and not _UILayoutGuide views
let embeddedViewController = EmbeddedViewController()
let embeddedView = embeddedViewController.view!
self.addChild(embeddedViewController)
embeddedView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(embeddedView)
embeddedViewController.didMove(toParent: self)
NSLayoutConstraint.activate([
embeddedView.topAnchor.constraint(equalTo: self.view.topAnchor),
embeddedView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
])
// Add tvOS-specific guides and constraints
#if os(tvOS)
AutoLayoutGuidesViewController.customFocusGuide(withFocusedView: embeddedViewController.centerView, addedTo: self.view, between: self.view.leftAnchor, and: readableContentGuide.leftAnchor)
AutoLayoutGuidesViewController.customFocusGuide(withFocusedView: self.focusableView, addedTo: self.view, between: readableContentGuide.rightAnchor, and: self.view.rightAnchor)
NSLayoutConstraint.activate([
self.bottomLabel.bottomAnchor.constraint(lessThanOrEqualTo: self.focusableImageView.focusedFrameGuide.topAnchor, constant: -8)
])
#endif
}
// MARK: - Private
@IBOutlet private weak var topLeftView: UIView!
@IBOutlet private weak var topRightView: UIView!
@IBOutlet private weak var bottomLeftView: UIView!
@IBOutlet private weak var bottomRightView: UIView!
@IBOutlet private weak var topLabel: UILabel!
@IBOutlet private weak var bottomLabel: UILabel!
#if os(tvOS)
@IBOutlet private weak var focusableView: UIView!
@IBOutlet private weak var focusableImageView: UIImageView!
#endif
@discardableResult
private static func customLayoutGuide(addedTo view: UIView) -> UILayoutGuide {
let guide = UILayoutGuide()
view.addLayoutGuide(guide)
NSLayoutConstraint.activate([
guide.heightAnchor.constraint(equalToConstant: 50),
guide.leadingAnchor.constraint(equalTo: view.leadingAnchor),
guide.trailingAnchor.constraint(equalTo: view.trailingAnchor),
guide.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
return guide
}
@discardableResult
private static func customFocusGuide(withFocusedView focusedView: UIView, addedTo view: UIView, between leftAnchor: NSLayoutXAxisAnchor, and rightAnchor: NSLayoutXAxisAnchor) -> UIFocusGuide {
let guide = UIFocusGuide()
view.addLayoutGuide(guide)
if #available(iOS 10.0, tvOS 10.0, *) {
guide.preferredFocusEnvironments = [ focusedView ]
} else {
guide.preferredFocusedView = focusedView
}
NSLayoutConstraint.activate([
guide.topAnchor.constraint(equalTo: view.topAnchor),
guide.bottomAnchor.constraint(equalTo: view.bottomAnchor),
guide.leftAnchor.constraint(equalTo: leftAnchor),
guide.rightAnchor.constraint(equalTo: rightAnchor)
])
return guide
}
// MARK: - Manually embedded view controller
final private class EmbeddedViewController: UIViewController {
var centerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
#if os(iOS)
let centerView = CustomIntrinsicContentSizeView()
#else
let centerView = FocusableView()
#endif
centerView.backgroundColor = #colorLiteral(red: 0.796, green: 1, blue: 0.235, alpha: 1)
centerView.layer.cornerRadius = 2
centerView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(centerView)
self.centerView = centerView
NSLayoutConstraint.activate([
centerView.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor),
centerView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
centerView.widthAnchor.constraint(equalTo: self.view.widthAnchor)
])
#if os(iOS)
NSLayoutConstraint.activate([
centerView.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 8)
])
#else
NSLayoutConstraint.activate([
centerView.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 60),
centerView.widthAnchor.constraint(equalToConstant: 300),
centerView.heightAnchor.constraint(equalTo: centerView.widthAnchor)
])
#endif
}
}
}
// MARK: - Focusable view (tvOS)
@available(tvOS 9.0, iOS 9.0, *)
final class FocusableView: UIView {
override var canBecomeFocused: Bool {
return true
}
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
coordinator.addCoordinatedAnimations({
self.alpha = self.isFocused ? 0.5 : 1.0
})
}
}
| 565ba70f2bc29d8437b166c829bcc85e | 36.55814 | 194 | 0.748607 | false | false | false | false |
corey-lin/PlayMarvelAPI | refs/heads/develop | NameSHero/ResultViewModel.swift | mit | 1 | //
// ResultViewModel.swift
// NameSHero
//
// Created by coreylin on 3/5/16.
// Copyright © 2016 coreylin. All rights reserved.
//
import Foundation
import ReactiveCocoa
class ResultViewModel {
let finalScore: MutableProperty<Int>
let perfectScore = MutableProperty<Bool>(false)
let newRecordScore = MutableProperty<Bool>(false)
init() {
finalScore = MutableProperty<Int>(0)
}
init(_ score: Int) {
finalScore = MutableProperty<Int>(score)
finalScore.producer.startWithNext {
currentScore in
let recordScore: Int = NSUserDefaults.standardUserDefaults().integerForKey(Constants.RecordScoreKey)
if recordScore < currentScore {
self.newRecordScore.value = true
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: Constants.RecordScoreKey)
}
if currentScore == 100 {
self.perfectScore.value = true
}
}
}
}
| 78d93f2accd0bd7931bfea8b23a3c0e4 | 25.794118 | 106 | 0.700329 | false | false | false | false |
wireapp/wire-ios-sync-engine | refs/heads/develop | Tests/Source/Integration/ConversationTests+Deletion.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// 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 XCTest
class ConversationTests_Deletion: ConversationTestsBase {
func testThatDeletingAConversationAlsoDeletesItLocally_OnSuccessfulResponse() {
// GIVEN
createTeamAndConversations()
XCTAssertTrue(login())
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// WHEN
let conversationIsDeleted = expectation(description: "Team conversation is deleted")
let teamConversation = conversation(for: groupConversationWithWholeTeam)!
teamConversation.delete(in: userSession!, completion: { (result) in
if case .success = result {
conversationIsDeleted.fulfill()
} else {
XCTFail()
}
})
XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5))
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
XCTAssertTrue(teamConversation.isZombieObject)
}
func testThatDeletingAConversationIsNotDeletingItLocally_OnFailureResponse() {
// GIVEN
createTeamAndConversations()
XCTAssertTrue(login())
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
mockTransportSession.responseGeneratorBlock = {[weak self] request in
guard request.path == "/teams/\(self!.team.identifier)/conversations/\(self!.groupConversationWithWholeTeam.identifier)" else { return nil }
self?.mockTransportSession.responseGeneratorBlock = nil
return ZMTransportResponse(payload: nil, httpStatus: 403, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
}
// WHEN
let conversationDeletionFailed = expectation(description: "Team conversation deletion failed")
let teamConversation = conversation(for: groupConversationWithWholeTeam)!
teamConversation.delete(in: userSession!, completion: { (result) in
if case .failure = result {
conversationDeletionFailed.fulfill()
} else {
XCTFail()
}
})
XCTAssertTrue(waitForCustomExpectations(withTimeout: 0.5))
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
XCTAssertFalse(teamConversation.isZombieObject)
}
}
| c8d79c1afaea29af535e3a348aa09de4 | 37.818182 | 152 | 0.688525 | false | true | false | false |
grafiti-io/SwiftCharts | refs/heads/master | SwiftCharts/Layers/ChartBarsLayer.swift | apache-2.0 | 1 | //
// ChartBarsLayer.swift
// Examples
//
// Created by ischuetz on 17/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartBarModel {
open let constant: ChartAxisValue
open let axisValue1: ChartAxisValue
open let axisValue2: ChartAxisValue
open let bgColor: UIColor?
/**
- parameter constant:Value of coordinate which doesn't change between start and end of the bar - if the bar is horizontal, this is y, if it's vertical it's x.
- parameter axisValue1:Start, variable coordinate.
- parameter axisValue2:End, variable coordinate.
- parameter bgColor:Background color of bar.
*/
public init(constant: ChartAxisValue, axisValue1: ChartAxisValue, axisValue2: ChartAxisValue, bgColor: UIColor? = nil) {
self.constant = constant
self.axisValue1 = axisValue1
self.axisValue2 = axisValue2
self.bgColor = bgColor
}
}
class ChartBarsViewGenerator<T: ChartBarModel, U: ChartPointViewBar> {
let layer: ChartCoordsSpaceLayer
let barWidth: CGFloat
let horizontal: Bool
let viewGenerator: ChartBarsLayer<U>.ChartBarViewGenerator?
init(horizontal: Bool, layer: ChartCoordsSpaceLayer, barWidth: CGFloat, viewGenerator: ChartBarsLayer<U>.ChartBarViewGenerator?) {
self.layer = layer
self.horizontal = horizontal
self.barWidth = barWidth
self.viewGenerator = viewGenerator
}
func viewPoints(_ barModel: T, constantScreenLoc: CGFloat) -> (p1: CGPoint, p2: CGPoint) {
switch horizontal {
case true:
return (
CGPoint(x: layer.modelLocToScreenLoc(x: barModel.axisValue1.scalar), y: constantScreenLoc),
CGPoint(x: layer.modelLocToScreenLoc(x: barModel.axisValue2.scalar), y: constantScreenLoc))
case false:
return (
CGPoint(x: constantScreenLoc, y: layer.modelLocToScreenLoc(y: barModel.axisValue1.scalar)),
CGPoint(x: constantScreenLoc, y: layer.modelLocToScreenLoc(y: barModel.axisValue2.scalar)))
}
}
func constantScreenLoc(_ barModel: T) -> CGFloat {
return horizontal ? layer.modelLocToScreenLoc(y: barModel.constant.scalar) : layer.modelLocToScreenLoc(x: barModel.constant.scalar)
}
func viewPoints(_ barModel: T, constantScreenLoc constantScreenLocMaybe: CGFloat? = nil) -> (p1: CGPoint, p2: CGPoint) {
let constantScreenLoc = constantScreenLocMaybe ?? self.constantScreenLoc(barModel)
return viewPoints(barModel, constantScreenLoc: constantScreenLoc)
}
func generateView(_ barModel: T, constantScreenLoc constantScreenLocMaybe: CGFloat? = nil, bgColor: UIColor?, settings: ChartBarViewSettings, model: ChartBarModel, index: Int, groupIndex: Int, chart: Chart? = nil) -> U {
let viewPoints = self.viewPoints(barModel, constantScreenLoc: constantScreenLocMaybe)
return viewGenerator?(viewPoints.p1, viewPoints.p2, barWidth, bgColor, settings, model, index) ??
U(p1: viewPoints.p1, p2: viewPoints.p2, width: barWidth, bgColor: bgColor, settings: settings)
}
}
public struct ChartTappedBar {
public let model: ChartBarModel
public let view: ChartPointViewBar
public let layer: ChartCoordsSpaceLayer
}
open class ChartBarsLayer<T: ChartPointViewBar>: ChartCoordsSpaceLayer {
public typealias ChartBarViewGenerator = (_ p1: CGPoint, _ p2: CGPoint, _ width: CGFloat, _ bgColor: UIColor?, _ settings: ChartBarViewSettings, _ model: ChartBarModel, _ index: Int) -> T
fileprivate let bars: [ChartBarModel]
fileprivate let barWidth: CGFloat
fileprivate let horizontal: Bool
fileprivate let settings: ChartBarViewSettings
fileprivate var barViews: [(model: ChartBarModel, view: T)] = []
fileprivate var tapHandler: ((ChartTappedBar) -> Void)?
fileprivate var viewGenerator: ChartBarViewGenerator? // Custom bar views
fileprivate let mode: ChartPointsViewsLayerMode
fileprivate var barsGenerator: ChartBarsViewGenerator<ChartBarModel, T>?
public init(xAxis: ChartAxis, yAxis: ChartAxis, bars: [ChartBarModel], horizontal: Bool = false, barWidth: CGFloat, settings: ChartBarViewSettings, mode: ChartPointsViewsLayerMode = .scaleAndTranslate, tapHandler: ((ChartTappedBar) -> Void)? = nil, viewGenerator: ChartBarViewGenerator? = nil) {
self.bars = bars
self.horizontal = horizontal
self.barWidth = barWidth
self.settings = settings
self.mode = mode
self.tapHandler = tapHandler
self.viewGenerator = viewGenerator
super.init(xAxis: xAxis, yAxis: yAxis)
barsGenerator = ChartBarsViewGenerator(horizontal: horizontal, layer: self, barWidth: barWidth, viewGenerator: viewGenerator)
}
open override func chartInitialized(chart: Chart) {
super.chartInitialized(chart: chart)
guard let barsGenerator = barsGenerator else {return}
for (index, barModel) in bars.enumerated() {
let barView = barsGenerator.generateView(barModel, bgColor: barModel.bgColor, settings: isTransform ? settings.copy(animDuration: 0, animDelay: 0) : settings, model: barModel, index: index, groupIndex: 0, chart: chart)
barView.tapHandler = {[weak self] tappedBarView in guard let weakSelf = self else {return}
weakSelf.tapHandler?(ChartTappedBar(model: barModel, view: tappedBarView, layer: weakSelf))
}
barViews.append((barModel, barView))
addSubview(chart, view: barView)
}
}
func addSubview(_ chart: Chart, view: UIView) {
mode == .scaleAndTranslate ? chart.addSubview(view) : chart.addSubviewNoTransform(view)
}
open override func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) {
super.zoom(x, y: y, centerX: centerX, centerY: centerY)
updateForTransform()
}
open override func pan(_ deltaX: CGFloat, deltaY: CGFloat) {
super.pan(deltaX, deltaY: deltaY)
updateForTransform()
}
func updateForTransform() {
guard let barsGenerator = barsGenerator else {return}
switch mode {
case .scaleAndTranslate:
break
case .translate:
for (barModel, barView) in barViews {
let (p1, p2) = barsGenerator.viewPoints(barModel)
barView.updateFrame(p1, p2: p2)
}
}
}
open override func modelLocToScreenLoc(x: Double) -> CGFloat {
switch mode {
case .scaleAndTranslate:
return super.modelLocToScreenLoc(x: x)
case .translate:
return super.modelLocToContainerScreenLoc(x: x)
}
}
open override func modelLocToScreenLoc(y: Double) -> CGFloat {
switch mode {
case .scaleAndTranslate:
return super.modelLocToScreenLoc(y: y)
case .translate:
return super.modelLocToContainerScreenLoc(y: y)
}
}
}
| c1c1a456ab326310b0540760cfe23e84 | 39.179775 | 299 | 0.668205 | false | false | false | false |
DarthMike/YapDatabaseExtensions | refs/heads/master | Example/Todotastic/Carthage/Checkouts/hldb/Pods/BrightFutures/BrightFutures/Queue.swift | mit | 8 | // The MIT License (MIT)
//
// Copyright (c) 2014 Thomas Visser
//
// 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 Dispatch
/// Queue is a tiny wrapper around a Grand Central Dispatch queue.
/// Queue provides a nice syntax for scheduling (async) execution of closures.
///
/// q.async {
/// // executes asynchronously
/// }
///
///
/// It also simplifies executing a closure synchronously and getting the
/// return value from the closure:
///
/// let n = q.sync {
/// return 42
/// }
///
public struct Queue {
/// The queue that is bound to the main thread (`dispatch_get_main_queue()`)
public static let main = Queue(queue: dispatch_get_main_queue());
/// The global queue with default priority
public static let global = Queue(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))
/// The underlying `dispatch_queue_t`
private(set) public var underlyingQueue: dispatch_queue_t
/// Returns an execution context that asynchronously performs tasks on this queue
public var context: ExecutionContext {
return { task in
self.async(task)
}
}
/// Instantiates a new `Queue` with the given queue.
/// If `queue` is omitted, a serial queue with identifier "queue" is used.
public init(queue: dispatch_queue_t = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL)) {
self.underlyingQueue = queue
}
/// Synchronously executes the given closure on this queue.
/// Analogous to dispatch_sync(self.underlyingQueue, block)
public func sync(block: () -> ()) {
dispatch_sync(underlyingQueue, block)
}
/// Synchronously executes the given closure on this queue and returns
/// the return value of the given closure.
public func sync<T>(block: () -> T) -> T {
var res: T? = nil
sync {
res = block()
}
return res!;
}
/// Asynchronously executes the given closure on this queue.
/// Analogous to dispatch_async(self.underlyingQueue, block)
public func async(block: () -> ()) {
dispatch_async(underlyingQueue, block)
}
/// Asynchronously executes the given closure on this queue and
/// returns a future that will succeed with the result of the closure.
public func async<T>(block: () -> T) -> Future<T> {
let p = Promise<T>()
async {
p.success(block())
}
return p.future
}
/// Asynchronously executes the given closure on the queue after a delay
/// Identical to dispatch_after(dispatch_time, self.underlyingQueue, block)
public func after(delay: TimeInterval, block: () -> ()) {
dispatch_after(delay.dispatchTime, underlyingQueue, block)
}
/// Asynchronously executes the given closure on the queue after a delay
/// and returns a future that will succeed with the result of the closure.
/// Identical to dispatch_after(dispatch_time, self.underlyingQueue, block)
public func after<T>(delay: TimeInterval, block: () -> T) -> Future<T> {
let p = Promise<T>()
after(delay) {
p.success(block())
}
return p.future
}
}
| 7774dc7ff5b43dd51b7601d0f3d2ce19 | 35.389831 | 106 | 0.659059 | false | false | false | false |
uias/Pageboy | refs/heads/main | Sources/iOS/Extras/TransparentNavigationBar.swift | mit | 1 | //
// TransparentNavigationBar.swift
// Example iOS
//
// Created by Merrick Sapsford on 15/02/2017.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
class TransparentNavigationBar: UINavigationBar {
private let separatorView = UIView()
// MARK: Init
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
var titleTextAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.white]
titleTextAttributes[.font] = UIFont.systemFont(ofSize: 18.0, weight: UIFont.Weight.semibold)
self.titleTextAttributes = titleTextAttributes
self.tintColor = UIColor.white.withAlphaComponent(0.7)
self.setBackgroundImage(UIImage(), for: .default)
self.shadowImage = UIImage()
self.isTranslucent = true
separatorView.backgroundColor = UIColor.white.withAlphaComponent(0.5)
self.addSubview(separatorView)
separatorView.frame = CGRect(x: 0.0,
y: self.bounds.size.height - 1.0,
width: self.bounds.size.width, height: 0.5)
}
// MARK: Lifecycle
override func layoutSubviews() {
super.layoutSubviews()
separatorView.frame = CGRect(x: 0.0,
y: self.bounds.size.height - 1.0,
width: self.bounds.size.width, height: 0.5)
}
}
| cce043fce2fd4b64d1e0022a84f972a6 | 29.735849 | 100 | 0.585021 | false | false | false | false |
AnarchyTools/atfoundation | refs/heads/master | tests/string/replace.swift | apache-2.0 | 1 | // Copyright (c) 2016 Anarchy Tools Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import atfoundation
class ReplaceTests: XCTestCase {
// MARK: New strings
func testNewStringSubstring() {
let s = "Hello World!"
XCTAssert(s.replacing(searchTerm: "World", replacement: "You") == "Hello You!")
}
func testNewStringSubstringWithEmpty() {
let s = "Hello World!"
XCTAssert(s.replacing(searchTerm: " World", replacement: "") == "Hello!")
}
func testNewStringEmptySubstring() {
let s = "Hello World!"
XCTAssert(s.replacing(searchTerm: "", replacement: "You") == "Hello World!")
}
func testNewStringRange() {
let s = "Hello World!"
XCTAssert(s.replacing(range: s.index(s.startIndex, offsetBy: 6)..<s.index(s.startIndex, offsetBy: 6+5), replacement: "You") == "Hello You!")
}
func testNewStringRangeWithEmpty() {
let s = "Hello World!"
XCTAssert(s.replacing(range: s.index(s.startIndex, offsetBy: 5)..<s.index(s.startIndex, offsetBy: 6+5), replacement: "") == "Hello!")
}
func testNewStringReplacingEnd() {
let s = "Hello World!"
XCTAssert(s.replacing(searchTerm: "World!", replacement: "You!") == "Hello You!")
}
// MARK: String modification
func testModifySubstring() {
var s = "Hello World!"
s.replace(searchTerm: "World", replacement: "You")
XCTAssert(s == "Hello You!")
}
func testModifySubstringWithEmpty() {
var s = "Hello World!"
s.replace(searchTerm: " World", replacement: "")
XCTAssert(s == "Hello!")
}
func testModifyEmptySubstring() {
var s = "Hello World!"
s.replace(searchTerm: "", replacement: "You")
XCTAssert(s == "Hello World!")
}
func testModifyRange() {
var s = "Hello World!"
s.replace(range: s.index(s.startIndex, offsetBy: 6)..<s.index(s.startIndex, offsetBy: 6+5), replacement: "You")
XCTAssert(s == "Hello You!")
}
func testModifyRangeWithEmpty() {
var s = "Hello World!"
s.replace(range: s.index(s.startIndex, offsetBy: 5)..<s.index(s.startIndex, offsetBy: 6+5), replacement: "")
XCTAssert(s == "Hello!")
}
func testModifyStringReplacingEnd() {
var s = "Hello World!"
s.replace(searchTerm: "World!", replacement: "You!")
XCTAssert(s == "Hello You!")
}
}
extension ReplaceTests {
static var allTests : [(String, (ReplaceTests) -> () throws -> Void)] {
return [
("testNewStringSubstring", testNewStringSubstring),
("testNewStringSubstringWithEmpty", testNewStringSubstringWithEmpty),
("testNewStringEmptySubstring", testNewStringEmptySubstring),
("testNewStringRange", testNewStringRange),
("testNewStringRangeWithEmpty", testNewStringRangeWithEmpty),
("testNewStringReplacingEnd", testNewStringReplacingEnd),
("testModifySubstring", testModifySubstring),
("testModifySubstringWithEmpty", testModifySubstringWithEmpty),
("testModifyEmptySubstring", testModifyEmptySubstring),
("testModifyRange", testModifyRange),
("testModifyRangeWithEmpty", testModifyRangeWithEmpty),
("testModifyStringReplacingEnd", testModifyStringReplacingEnd),
]
}
}
| 0a04b24018f719ce0e63069747ceaa39 | 34.763636 | 148 | 0.639298 | false | true | false | false |
wj2061/ios7ptl-swift3.0 | refs/heads/master | ch21-Text/Columns/Columns/ColumnView.swift | mit | 1 | //
// ColumnView.swift
// Columns
//
// Created by wj on 15/11/28.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
let kColumnCount = 3
class ColumnView: UIView {
var mode = 0
var attributedString:NSAttributedString?
fileprivate func copyColumnRects()->[CGRect]{
let bounds = self.bounds.insetBy(dx: 20, dy: 20)
var columnRects = Array.init(repeating: CGRect.zero, count: 3)
let columnWidth = bounds.width / CGFloat( kColumnCount)
for i in 0..<kColumnCount{
columnRects[i] = CGRect(x: CGFloat(i)*columnWidth + bounds.minX, y: bounds.minY, width: columnWidth, height: bounds.height)
columnRects[i] = columnRects[i].insetBy(dx: 10, dy: 10)
}
return columnRects
}
func copyPaths()->[CGPath]{
var paths = [CGPath]()
let columnRects = copyColumnRects()
switch mode{
case 0:
for i in 0..<kColumnCount{
let path = CGPath(rect: columnRects[i], transform: nil)
paths.append(path)
}
case 1:
let path = CGMutablePath()
for i in 0..<kColumnCount{
path.addRect(columnRects[i]);
}
paths.append(path)
case 2:
var path = CGMutablePath()
path.move(to: CGPoint(x:30, y:0));
path.addLine(to: CGPoint(x: 344, y: 30));// Bottom right
path.addLine(to: CGPoint(x: 344, y: 400));
path.addLine(to: CGPoint(x: 200, y: 400));
path.addLine(to: CGPoint(x: 200, y: 800));
path.addLine(to: CGPoint(x: 344, y: 800));
path.addLine(to: CGPoint(x: 344, y: 944));// Top right
path.addLine(to: CGPoint(x: 30, y: 944));// Top left
path.closeSubpath()
paths.append(path)
path = CGMutablePath()
path.move(to: CGPoint(x:700, y:30));
path.addLine(to: CGPoint(x: 360, y: 30));
path.addLine(to: CGPoint(x: 360, y: 400));
path.addLine(to: CGPoint(x: 500, y: 400));
path.addLine(to: CGPoint(x: 500, y: 800));
path.addLine(to: CGPoint(x: 360, y: 800));
path.addLine(to: CGPoint(x: 360, y: 944));// Top left
path.addLine(to: CGPoint(x: 700, y: 944));// Top right
path.closeSubpath()
paths.append(path)
case 3:
let path = CGPath(ellipseIn: bounds.insetBy(dx: 30, dy: 30), transform: nil)
paths.append(path)
default:
break
}
print(paths.count)
return paths
}
override init(frame: CGRect) {
super.init(frame: frame)
let transform = CGAffineTransform(scaleX: 1, y: -1)
transform.translatedBy(x: 0, y: -self.bounds.size.height)
self.transform = transform
backgroundColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
if attributedString == nil {return}
let context = UIGraphicsGetCurrentContext()
context!.textMatrix = CGAffineTransform.identity
let framesetter = CTFramesetterCreateWithAttributedString(attributedString!)
let paths = copyPaths()
var charIndex = 0
for i in 0..<paths.count{
let path = paths[i]
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(charIndex, 0), path, nil)
CTFrameDraw(frame, context!)
let frameRange = CTFrameGetVisibleStringRange(frame)
charIndex += frameRange.length
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
mode = (mode + 1)%4
setNeedsDisplay()
}
}
| 267a28934bade1bfe5df64102ffd945d | 32.459677 | 135 | 0.550735 | false | false | false | false |
tlax/GaussSquad | refs/heads/master | GaussSquad/Model/Help/Calculator/MHelpCalculator.swift | mit | 1 | import Foundation
class MHelpCalculator:MHelp
{
init()
{
let itemPascal:MHelpCalculatorItemPascal = MHelpCalculatorItemPascal()
let itemOptions:MHelpCalculatorItemOptions = MHelpCalculatorItemOptions()
let itemFunctions:MHelpCalculatorItemFunctions = MHelpCalculatorItemFunctions()
let itemUndo:MHelpCalculatorItemUndo = MHelpCalculatorItemUndo()
let items:[MHelpItem] = [
itemPascal,
itemOptions,
itemFunctions,
itemUndo
]
super.init(items:items)
}
}
| 7419656b806db938bff16195e7de3f3b | 26.952381 | 87 | 0.649063 | false | false | false | false |
ktmswzw/FeelClient | refs/heads/master | FeelingClient/common/utils/JWTTools.swift | mit | 1 | //
// JWTTools.swift
// Temp
//
// Created by vincent on 8/2/16.
// Copyright © 2016 xecoder. All rights reserved.
//
import Foundation
import JWT
class JWTTools {
let SECERT: String = "FEELING_ME007"
let JWTDEMOTOKEN: String = "JWTDEMOTOKEN"
let FEELINGUSERNAME: String = "FEELINGUSERNAME"
let FEELINGPSWORD: String = "FEELINGPSWORD"
let JWTDEMOTEMP: String = "JWTDEMOTEMP"
let JWTSIGN: String = "JWTSIGN"
let AUTHORIZATION_STR: String = "Authorization"
let IMTOKENTEMP: String = "IMTOKENTEMP"
let USERID: String = "FEELING_USERID"
let USERINFO: String = "FEELING_USERINFO"
var appUsername: String {
get {
if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(FEELINGUSERNAME) as? String {
return returnValue
} else {
return "" //Default value
}
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: FEELINGUSERNAME)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
var appPwd: String {
get {
if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(FEELINGPSWORD) as? String {
return returnValue
} else {
return "" //Default value
}
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: FEELINGPSWORD)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
var token: String {
get {
if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(JWTDEMOTOKEN) as? String {
return returnValue
} else {
return "" //Default value
}
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: JWTDEMOTOKEN)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
var sign: String {
get {
if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(JWTSIGN) as? String {
return returnValue
} else {
return "" //Default value
}
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: JWTSIGN)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
var jwtTemp: String {
get {
if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(JWTDEMOTEMP) as? String {
// NSLog("\(returnValue)")
return returnValue
} else {
return "" //Default value
}
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: JWTDEMOTEMP)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
var imToken: String {
get {
if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(IMTOKENTEMP) as? String {
return returnValue
} else {
return "" //Default value
}
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: IMTOKENTEMP)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
var userId: String {
get {
if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(USERID) as? String {
return returnValue
} else {
return "" //Default value
}
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: USERID)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
var userName: String {
get {
if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey(USERINFO) as? String {
return returnValue
} else {
return "" //Default value
}
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: USERINFO)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func getHeader(tokenNew: String, myDictionary: Dictionary<String, String> ) -> [String : String] {
if jwtTemp.isEmpty || !myDictionary.isEmpty {//重复使用上次计算结果
let jwt = JWT.encode(.HS256(SECERT)) { builder in
for (key, value) in myDictionary {
builder[key] = value
}
builder["token"] = tokenNew
}
if !myDictionary.isEmpty && tokenNew == self.token {//不填充新数据
jwtTemp = jwt
}
return [ AUTHORIZATION_STR : jwt ]
}
else {
return [ AUTHORIZATION_STR : jwtTemp ]
}
}
} | 6423704b5e38f99519134e6a8d861004 | 31.4 | 113 | 0.557658 | false | false | false | false |
IAskWind/IAWExtensionTool | refs/heads/main | Examples/Pippin/Pods/SwiftMessages/SwiftMessages/KeyboardTrackingView.swift | apache-2.0 | 3 | //
// KeyboardTrackingView.swift
// SwiftMessages
//
// Created by Timothy Moose on 5/20/19.
// Copyright © 2019 SwiftKick Mobile. All rights reserved.
//
import UIKit
public protocol KeyboardTrackingViewDelegate: class {
func keyboardTrackingViewWillChange(change: KeyboardTrackingView.Change, userInfo: [AnyHashable : Any])
func keyboardTrackingViewDidChange(change: KeyboardTrackingView.Change, userInfo: [AnyHashable : Any])
}
/// A view that adjusts it's height based on keyboard hide and show notifications.
/// Pin it to the bottom of the screen using Auto Layout and then pin views that
/// should avoid the keyboard to the top of it. Supply an instance of this class
/// on `SwiftMessages.Config.keyboardTrackingView` or `SwiftMessagesSegue.keyboardTrackingView`
/// for automatic keyboard avoidance for the entire SwiftMessages view or view controller.
open class KeyboardTrackingView: UIView {
public enum Change {
case show
case hide
case frame
}
public weak var delegate: KeyboardTrackingViewDelegate?
/// Typically, when a view controller is not being displayed, keyboard
/// tracking should be paused to avoid responding to keyboard events
/// caused by other view controllers or apps. Setting `isPaused = false` in
/// `viewWillAppear` and `isPaused = true` in `viewWillDisappear` usually works. This class
/// automatically pauses and resumes when the app resigns and becomes active, respectively.
open var isPaused = false {
didSet {
if !isPaused {
isAutomaticallyPaused = false
}
}
}
/// The margin to maintain between the keyboard and the top of the view.
@IBInspectable open var topMargin: CGFloat = 0
override public init(frame: CGRect) {
super.init(frame: frame)
postInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func awakeFromNib() {
super.awakeFromNib()
postInit()
}
private var isAutomaticallyPaused = false
private var heightConstraint: NSLayoutConstraint!
private func postInit() {
translatesAutoresizingMaskIntoConstraints = false
heightConstraint = heightAnchor.constraint(equalToConstant: 0)
heightConstraint.isActive = true
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(pause), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(resume), name: UIApplication.didBecomeActiveNotification, object: nil)
backgroundColor = .clear
}
@objc private func keyboardWillChangeFrame(_ notification: Notification) {
show(change: .frame, notification)
}
@objc private func keyboardWillShow(_ notification: Notification) {
show(change: .show, notification)
}
@objc private func keyboardWillHide(_ notification: Notification) {
guard !(isPaused || isAutomaticallyPaused),
let userInfo = (notification as NSNotification).userInfo else { return }
guard heightConstraint.constant != 0 else { return }
delegate?.keyboardTrackingViewWillChange(change: .hide, userInfo: userInfo)
animateKeyboardChange(change: .hide, height: 0, userInfo: userInfo)
}
@objc private func pause() {
isAutomaticallyPaused = true
}
@objc private func resume() {
isAutomaticallyPaused = false
}
private func show(change: Change, _ notification: Notification) {
guard !(isPaused || isAutomaticallyPaused),
let userInfo = (notification as NSNotification).userInfo,
let value = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardRect = value.cgRectValue
let thisRect = convert(bounds, to: nil)
let newHeight = max(0, thisRect.maxY - keyboardRect.minY) + topMargin
guard heightConstraint.constant != newHeight else { return }
delegate?.keyboardTrackingViewWillChange(change: change, userInfo: userInfo)
animateKeyboardChange(change: change, height: newHeight, userInfo: userInfo)
}
private func animateKeyboardChange(change: Change, height: CGFloat, userInfo: [AnyHashable: Any]) {
self.heightConstraint.constant = height
if let durationNumber = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber,
let curveNumber = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber {
CATransaction.begin()
CATransaction.setCompletionBlock {
self.delegate?.keyboardTrackingViewDidChange(change: change, userInfo: userInfo)
}
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(durationNumber.doubleValue)
UIView.setAnimationCurve(UIView.AnimationCurve(rawValue: curveNumber.intValue)!)
UIView.setAnimationBeginsFromCurrentState(true)
self.superview?.layoutIfNeeded()
UIView.commitAnimations()
CATransaction.commit()
}
}
}
| 2286d61d03512823d713134c9618eacf | 43.069767 | 163 | 0.706772 | false | false | false | false |
S2dentik/Taylor | refs/heads/master | TaylorFrameworkTests/EasterEggsTests/PacmanTests/PacmanRunnerTests.swift | mit | 4 | //
// PacmanRunnerTests.swift
// Taylor
//
// Created by Dmitrii Celpan on 11/11/15.
// Copyright © 2015 YOPESO. All rights reserved.
//
import Quick
import Nimble
@testable import TaylorFramework
class MockPacmanRunner: PacmanRunner {
var play = false
override func input() -> String { return (play) ? "Y" : "N" }
override func runEasterEgg(_ paths: [Path]) { }
}
class PacmanRunnerTests: QuickSpec {
override func spec() {
describe("PacmanRunner") {
var pacmanRunner : PacmanRunner!
beforeEach {
pacmanRunner = PacmanRunner()
}
afterEach {
pacmanRunner = nil
}
it("should remove spaces and new lines from given string") {
let initialString = "\n \n string \n\n\t"
expect(pacmanRunner.formatInputString(initialString)).to(equal("string"))
}
it("should not crash if user choose to play pacman") {
let mockPacmanRunner = MockPacmanRunner()
mockPacmanRunner.play = true
mockPacmanRunner.runEasterEggPrompt()
}
it("should not crash if user choose to not play pacman") {
let mockPacmanRunner = MockPacmanRunner()
mockPacmanRunner.play = false
mockPacmanRunner.runEasterEggPrompt()
}
it("should not crash when given empty array of paths") {
let pacmanRunner = PacmanRunner()
pacmanRunner.runEasterEgg([])
}
}
}
}
| 7e6b32207705db6938f3ec2590ce8355 | 27.016129 | 89 | 0.52274 | false | false | false | false |
BenziAhamed/Nevergrid | refs/heads/master | NeverGrid/Source/RobotMoveOnce.swift | isc | 1 | //
// RobotMoveOnce.swift
// NeverGrid
//
// Created by Benzi on 24/09/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
import Foundation
import SpriteKit
class RobotMoveOnce : MoveOnce {
override var description:String { return "RobotMoveOnce" }
override init(entity: Entity, world: WorldMapper, moveStrategy:EnemyMoveStrategy) {
super.init(entity: entity, world: world, moveStrategy:moveStrategy)
}
override func perform() -> SKAction? {
let moveAction = super.perform()
if moveAction != nil {
// since a robot moves in an animated fashion lets get that on the way
// move body up
// do the move
// after move completes we need to move body down
// base move action takes ActionFactory.Timing.EntityMove time
let sprite = world.sprite.get(entity)
let robotHeight = sprite.node.size.height * (128.0/168.0)
let timeForBodyAnimation = NSTimeInterval(0.2)
let bodyAnimation =
SKAction.moveByX(0.0, y: 0.125*robotHeight, duration: timeForBodyAnimation) // move up
.followedBy(SKAction.waitForDuration(ActionFactory.Timing.EntityMove)) // wait for move to complete
.followedBy(SKAction.moveByX(0.0, y: -0.125*robotHeight, duration: timeForBodyAnimation))
let body = sprite.node.childNodeWithName("body")!
body.runAction(bodyAnimation)
let modifiedMoveAction =
SKAction.waitForDuration(timeForBodyAnimation)
.followedBy(moveAction!)
return modifiedMoveAction
}
else {
return nil
}
}
} | bafeb2b97a4471ba759d32aee377b2b0 | 31.836364 | 115 | 0.598892 | false | false | false | false |
chaoyang805/DoubanMovie | refs/heads/master | DoubanMovie/LoadingPageControl.swift | apache-2.0 | 1 | /*
* Copyright 2016 chaoyang805 [email protected]
*
* 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
class LoadingPageControl: UIPageControl, LoadingEffect {
private(set) var isLoading: Bool = false
private let animateDuration: TimeInterval = 0.3
private let animateOffset: CGFloat = 8
func beginLoading() {
if isLoading {
return
}
isLoading = true
let dots = self.subviews
for (index, dot) in dots.enumerated() {
let delay = Double(index) * (animateDuration / 2)
animateView(dot, withDuration: animateDuration, afterDelay: delay)
}
}
func endLoading() {
isLoading = false
}
func animateView(_ dot: UIView, withDuration duration: TimeInterval, afterDelay delay: TimeInterval) {
return UIView.animate(
withDuration: duration,
delay: delay,
options:[UIViewAnimationOptions.curveEaseIn],
animations: {
dot.center.y -= self.animateOffset
},
completion: { done in
return UIView.animate(
withDuration: duration,
delay: 0,
options: [UIViewAnimationOptions.curveEaseOut],
animations: {
dot.center.y += self.animateOffset
},
completion: { [weak self](done) in
guard let `self` = self , self.isLoading else { return }
self.animateView(dot,
withDuration: duration,
afterDelay: Double(self.subviews.count) / 2 * duration)
})
})
}
}
| f7d9fb7d023883c2c650c8fec336e5fa | 32.774648 | 106 | 0.553378 | false | false | false | false |
brksp/BSNotesApp | refs/heads/master | BSNotesApp/BSNotesApp/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// BSNotesApp
//
// Created by Burak SIPCIKOGLU on 17/05/2017.
// Copyright © 2017 burak. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "BSNotesApp")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 49f5ddfa2d24112ddff41b4f621601e1 | 48.419355 | 285 | 0.686249 | false | false | false | false |
p0dee/PDAlertView | refs/heads/master | PDAlertView/AlertView.swift | gpl-2.0 | 1 | //
// AlertView.swift
// AlertViewMock
//
// Created by Takeshi Tanaka on 12/19/15.
// Copyright © 2015 Takeshi Tanaka. All rights reserved.
//
//import Foundation
import UIKit
public class AlertView: UIView, AlertBodyViewDelegate {
private let backgroundView = AlertBackgroundView()
private let bodyView = AlertBodyView()
private var actions = [AlertAction]()
private var backgroundBottomConstraint: NSLayoutConstraint?
var accessoryView: UIView? {
didSet {
guard accessoryView != oldValue else {
return
}
for v in bodyView.accessoryContentView.subviews {
v.removeFromSuperview()
}
if let accessoryView = accessoryView {
bodyView.accessoryContentView.addSubview(accessoryView)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
setupConstraints()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardHeightDidChange(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardHeightDidChange(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience public init(title: String?, message: String?) {
self.init()
bodyView.title = title
bodyView.message = message
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override public func didMoveToSuperview() {
guard self.superview != nil else { return }
self.translatesAutoresizingMaskIntoConstraints = false
let cstrs = NSLayoutConstraint.constraintsToFillSuperview(self)
NSLayoutConstraint.activate(cstrs)
}
private func setupViews() {
self.backgroundColor = UIColor(white: 0.0, alpha: 0.4)
backgroundView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(backgroundView)
bodyView.translatesAutoresizingMaskIntoConstraints = false
bodyView.delegate = self
backgroundView.addSubview(bodyView)
}
private func setupConstraints() {
var cstrs = [NSLayoutConstraint]()
cstrs += NSLayoutConstraint.constraintsToFillSuperview(backgroundView)
backgroundBottomConstraint = cstrs.last
cstrs.append(bodyView.centerXAnchor.constraint(equalTo: backgroundView.centerXAnchor))
cstrs.append(bodyView.centerYAnchor.constraint(equalTo: backgroundView.centerYAnchor))
NSLayoutConstraint.activate(cstrs)
}
@objc private func keyboardHeightDidChange(_ sender: NSNotification) {
guard let backgroundBottomConstraint = backgroundBottomConstraint else {
return
}
var delta: CGFloat = 0
switch sender.name {
case NSNotification.Name.UIKeyboardWillShow:
if let info = sender.userInfo, let sz = (info[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue {
delta = -sz.height
}
case NSNotification.Name.UIKeyboardWillHide:
delta = 0
default:
break
}
backgroundBottomConstraint.constant = delta
}
//MARK: public interface
public func addAction(_ action: AlertAction) {
actions.append(action)
bodyView.addAction(action)
}
public func showOn(targetView: UIView) {
targetView.addSubview(self)
let ratio = 320 / bodyView.intrinsicContentSize.width
self.alpha = 0.0
bodyView.alpha = 0.0
bodyView.transform = CGAffineTransform(scaleX: ratio, y: ratio)
UIView.animate(withDuration: 0.45, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .curveEaseInOut, animations: { () -> Void in
self.alpha = 1.0
self.bodyView.alpha = 1.0
self.bodyView.transform = .identity
}, completion: nil)
}
public func dismiss() {
UIView.animate(withDuration: 0.45, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .curveEaseOut, animations: { () -> Void in
self.alpha = 0.0
}, completion: { _ in
self.removeFromSuperview()
})
}
//MARK: <AlertBodyViewDelegate>
internal func bodyView(_ bodyView: AlertBodyView, didSelectedItemAtIndex index: Int) {
actions[index].handler?()
}
}
| cc0f2738d4d88dd13ca4fcc6968d514f | 34.938462 | 165 | 0.648116 | false | false | false | false |
darwin/textyourmom | refs/heads/master | TextYourMom/Airport.swift | mit | 1 | typealias AirportId = Int
enum AirportPerimeter : String {
case None = "none"
case Inner = "inner"
case Outer = "outer"
}
struct Airport {
var id: AirportId = 0
var name: String = ""
var city: String = ""
var country: String = ""
var latitude: Double = 0.0
var longitude: Double = 0.0
}
class AirportsVisitorState : Equatable, Printable {
var state = [AirportId:AirportPerimeter]()
func update(id:AirportId, _ perimeter: AirportPerimeter) {
if perimeter == .None {
state[id] = nil
return
}
state[id] = perimeter
}
func itemDescription(id:AirportId, _ perimeter: AirportPerimeter) -> String {
return "\(id):\(perimeter.rawValue)"
}
var description: String {
if state.count == 0 {
return "[no man's land]"
}
var parts = [String]()
for (id, perimeter) in state {
parts.append(itemDescription(id, perimeter))
}
return ", ".join(parts)
}
}
// MARK: serialization
extension AirportsVisitorState {
var partSeparator : Character {
get { return ":" }
}
var itemSeparator : Character {
get { return "," }
}
func serialize() -> String {
var parts = [String]()
for (id, perimeter) in state {
parts.append("\(id)\(partSeparator)\(perimeter.rawValue)")
}
return String(itemSeparator).join(parts)
}
func unserialize(data: String) {
state.removeAll(keepCapacity: true)
let items = split(data) {$0 == self.itemSeparator}
for item in items {
let pieces = split(item) {$0 == self.partSeparator}
if pieces.count != 2 {
log("!!! unable to unserialize pair: \(item)")
continue
}
let id = pieces[0].toInt()
let perimeter = AirportPerimeter.init(rawValue:pieces[1])
if id != nil && perimeter != nil {
state[id!] = perimeter!
} else {
log("!!! unable to unserialize pair: \(item)")
}
}
}
}
func ==(lhs: AirportsVisitorState, rhs: AirportsVisitorState) -> Bool {
return lhs.state == rhs.state
}
struct AirportVisitChange {
var before: AirportPerimeter
var after: AirportPerimeter
}
class AirportsVisitorStateDiff : Printable {
var diff = [AirportId:AirportVisitChange]()
init(oldState: AirportsVisitorState, newState:AirportsVisitorState) {
let oldIds = $.keys(oldState.state)
let newIds = $.keys(newState.state)
for id in $.difference(oldIds, newIds) {
diff[id] = AirportVisitChange(before:oldState.state[id]!, after:.None)
}
for id in $.difference(newIds, oldIds) {
diff[id] = AirportVisitChange(before:.None, after:newState.state[id]!)
}
for id in $.intersection(newIds, oldIds) {
let change = AirportVisitChange(before:oldState.state[id]!, after:newState.state[id]!)
if change.before != change.after {
diff[id] = change
}
}
}
var description: String {
if diff.count == 0 {
return "- no change -"
}
var parts = [String]()
for (id, change) in diff {
parts.append("\(id):\(change.before.rawValue)->\(change.after.rawValue)")
}
return ", ".join(parts)
}
var empty : Bool {
return diff.count == 0
}
} | bdba01426aacd695457c0c8cfeab92c7 | 26.424242 | 98 | 0.542691 | false | false | false | false |
haranicle/RealmRelationsSample | refs/heads/master | Carthage/Checkouts/realm-cocoa/Realm/Tests/Swift/SwiftTestCase.swift | mit | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm
func testRealmPath() -> String {
return realmPathForFile("test.realm")
}
func defaultRealmPath() -> String {
return realmPathForFile("default.realm")
}
func realmPathForFile(fileName: String) -> String {
#if os(iOS)
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
return (paths[0] as String) + "/" + fileName
#else
return fileName
#endif
}
func realmLockPath(path: String) -> String {
return path + ".lock"
}
func deleteRealmFilesAtPath(path: String) {
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(path) {
let succeeded = NSFileManager.defaultManager().removeItemAtPath(path, error: nil)
assert(succeeded, "Unable to delete realm")
}
let lockPath = realmLockPath(path)
if fileManager.fileExistsAtPath(lockPath) {
let succeeded = NSFileManager.defaultManager().removeItemAtPath(lockPath, error: nil)
assert(succeeded, "Unable to delete realm")
}
}
func realmWithTestPathAndSchema(schema: RLMSchema?) -> RLMRealm {
return RLMRealm(path: testRealmPath(), key: nil, readOnly: false, inMemory: false, dynamic: false, schema: schema, error: nil)
}
func dynamicRealmWithTestPathAndSchema(schema: RLMSchema?) -> RLMRealm {
return RLMRealm(path: testRealmPath(), key: nil, readOnly: false, inMemory: false, dynamic: true, schema: schema, error: nil)
}
class SwiftTestCase: XCTestCase {
func realmWithTestPath() -> RLMRealm {
return RLMRealm(path: testRealmPath(), readOnly: false, error: nil)
}
override func setUp() {
super.setUp()
// Delete realm files
deleteRealmFilesAtPath(defaultRealmPath())
deleteRealmFilesAtPath(testRealmPath())
}
override func tearDown() {
super.tearDown()
// Reset Realm cache
RLMRealm.resetRealmState()
// Delete realm files
deleteRealmFilesAtPath(defaultRealmPath())
deleteRealmFilesAtPath(testRealmPath())
}
}
| 116d054209602f95c0b720e5285cfe1c | 30.696629 | 130 | 0.661113 | false | true | false | false |
ahoppen/swift | refs/heads/main | test/Constraints/dictionary_literal.swift | apache-2.0 | 9 | // RUN: %target-typecheck-verify-swift
final class DictStringInt : ExpressibleByDictionaryLiteral {
typealias Key = String
typealias Value = Int
init(dictionaryLiteral elements: (String, Int)...) { }
}
final class MyDictionary<K, V> : ExpressibleByDictionaryLiteral {
typealias Key = K
typealias Value = V
init(dictionaryLiteral elements: (K, V)...) { }
}
func useDictStringInt(_ d: DictStringInt) {}
func useDict<K, V>(_ d: MyDictionary<K,V>) {}
// Concrete dictionary literals.
useDictStringInt(["Hello" : 1])
useDictStringInt(["Hello" : 1, "World" : 2])
useDictStringInt(["Hello" : 1, "World" : 2.5])
// expected-error@-1 {{cannot convert value of type 'Double' to expected dictionary value type 'DictStringInt.Value' (aka 'Int')}}
useDictStringInt([4.5 : 2])
// expected-error@-1 {{cannot convert value of type 'Double' to expected dictionary key type 'DictStringInt.Key' (aka 'String')}}
useDictStringInt([nil : 2])
// expected-error@-1 {{'nil' is not compatible with expected dictionary key type 'DictStringInt.Key' (aka 'String')}}
useDictStringInt([7 : 1, "World" : 2])
// expected-error@-1 {{cannot convert value of type 'Int' to expected dictionary key type 'DictStringInt.Key' (aka 'String')}}
useDictStringInt(["Hello" : nil])
// expected-error@-1 {{'nil' is not compatible with expected dictionary value type 'DictStringInt.Value' (aka 'Int')}}
typealias FuncBoolToInt = (Bool) -> Int
let dict1: MyDictionary<String, FuncBoolToInt> = ["Hello": nil]
// expected-error@-1 {{'nil' is not compatible with expected dictionary value type 'MyDictionary<String, FuncBoolToInt>.Value' (aka '(Bool) -> Int')}}
// Generic dictionary literals.
useDict(["Hello" : 1])
useDict(["Hello" : 1, "World" : 2])
useDict(["Hello" : 1.5, "World" : 2])
useDict([1 : 1.5, 3 : 2.5])
// Fall back to Swift.Dictionary<K, V> if no context is otherwise available.
var a = ["Hello" : 1, "World" : 2]
var a2 : Dictionary<String, Int> = a
var a3 = ["Hello" : 1]
var b = [1 : 2, 1.5 : 2.5]
var b2 : Dictionary<Double, Double> = b
var b3 = [1 : 2.5]
// <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error
// expected-note @+1 {{did you mean to use a dictionary literal instead?}}
var _: MyDictionary<String, (Int) -> Int>? = [ // expected-error {{dictionary of type 'MyDictionary<String, (Int) -> Int>' cannot be initialized with array literal}}
"closure_1" as String, {(Int) -> Int in 0},
"closure_2", {(Int) -> Int in 0}]
var _: MyDictionary<String, Int>? = ["foo", 1] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{43-44=:}}
var _: MyDictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{43-44=:}} {{53-54=:}}
var _: MyDictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{none}}
var _: MyDictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'MyDictionary<String, Int>.Value' (aka 'Int')}}
// <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better
var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}}
var _ = useDictStringInt([]) // expected-error {{use [:] to get an empty dictionary literal}} {{27-27=:}}
var _: [[Int: Int]] = [[]] // expected-error {{use [:] to get an empty dictionary literal}} {{25-25=:}}
var _: [[Int: Int]?] = [[]] // expected-error {{use [:] to get an empty dictionary literal}} {{26-26=:}}
var assignDict = [1: 2]
assignDict = [] // expected-error {{use [:] to get an empty dictionary literal}} {{15-15=:}}
var _: [Int: Int] = [1] // expected-error {{dictionary of type '[Int : Int]' cannot be initialized with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{23-23=: <#value#>}}
var _: [Float: Int] = [1] // expected-error {{dictionary of type '[Float : Int]' cannot be initialized with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{25-25=: <#value#>}}
var _: [Int: Int] = ["foo"] // expected-error {{dictionary of type '[Int : Int]' cannot be initialized with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{27-27=: <#value#>}}
// expected-error@-2 {{cannot convert value of type 'String' to expected dictionary key type 'Int'}}
var _ = useDictStringInt(["Key"]) // expected-error {{dictionary of type 'DictStringInt' cannot be used with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{32-32=: <#value#>}}
var _ = useDictStringInt([4]) // expected-error {{dictionary of type 'DictStringInt' cannot be used with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{28-28=: <#value#>}}
// expected-error@-2 {{cannot convert value of type 'Int' to expected dictionary key type 'DictStringInt.Key' (aka 'String')}}
var _: [[Int: Int]] = [[5]] // expected-error {{dictionary of type '[Int : Int]' cannot be used with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{26-26=: <#value#>}}
var _: [[Int: Int]] = [["bar"]] // expected-error {{dictionary of type '[Int : Int]' cannot be used with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{30-30=: <#value#>}}
// expected-error@-2 {{cannot convert value of type 'String' to expected dictionary key type 'Int'}}
assignDict = [1] // expected-error {{dictionary of type '[Int : Int]' cannot be used with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{16-16=: <#value#>}}
assignDict = [""] // expected-error {{dictionary of type '[Int : Int]' cannot be used with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{17-17=: <#value#>}}
// expected-error@-2 {{cannot convert value of type 'String' to expected dictionary key type 'Int'}}
func arrayLiteralDictionaryMismatch<T>(a: inout T) where T: ExpressibleByDictionaryLiteral, T.Key == Int, T.Value == Int {
a = [] // expected-error {{use [:] to get an empty dictionary literal}} {{8-8=:}}
a = [1] // expected-error {{dictionary of type 'T' cannot be used with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{9-9=: <#value#>}}
a = [""] // expected-error {{dictionary of type 'T' cannot be used with array literal}}
// expected-note@-1 {{did you mean to use a dictionary literal instead?}} {{10-10=: <#value#>}}
// expected-error@-2 {{cannot convert value of type 'String' to expected dictionary key type 'Int'}}
}
class A { }
class B : A { }
class C : A { }
func testDefaultExistentials() {
let _ = ["a" : 1, "b" : 2.5, "c" : "hello"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}}{{46-46= as [String : Any]}}
let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"]
let _ = ["a" : 1, "b" : nil, "c" : "hello"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[String : Any?]'; add explicit type annotation if this is intentional}}{{46-46= as [String : Any?]}}
let _: [String : Any?] = ["a" : 1, "b" : nil, "c" : "hello"]
let d2 = [:]
// expected-error@-1{{empty collection literal requires an explicit type}}
let _: Int = d2 // expected-error{{value of type '[AnyHashable : Any]'}}
let _ = ["a": 1,
"b": ["a", 2, 3.14159],
"c": ["a": 2, "b": 3.5]]
// expected-error@-3{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}}
let d3 = ["b" : B(), "c" : C()]
let _: Int = d3 // expected-error{{value of type '[String : A]'}}
let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[AnyHashable : Any]'}}
let _ = ["a" : "hello", 17 : "string"]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[AnyHashable : String]'}}
}
// SR-4952, rdar://problem/32330004 - Assertion failure during swift::ASTVisitor<::FailureDiagnosis,...>::visit
func rdar32330004_1() -> [String: Any] {
return ["a""one": 1, "two": 2, "three": 3] // expected-note {{did you mean to use a dictionary literal instead?}}
// expected-error@-1 {{expected ',' separator}}
// expected-error@-2 {{dictionary of type '[String : Any]' cannot be used with array literal}}
}
func rdar32330004_2() -> [String: Any] {
return ["a", 0, "one", 1, "two", 2, "three", 3]
// expected-error@-1 {{dictionary of type '[String : Any]' cannot be used with array literal}}
// expected-note@-2 {{did you mean to use a dictionary literal instead?}} {{14-15=:}} {{24-25=:}} {{34-35=:}} {{46-47=:}}
}
| d19e386987b4bfb16fa6ea6d1b17b352 | 54.242604 | 190 | 0.656598 | false | false | false | false |
raulriera/HuntingKit | refs/heads/master | HuntingKit/ImagesURL.swift | mit | 1 | //
// ImagesURL.swift
// HuntingKit
//
// Created by Raúl Riera on 24/04/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
public struct ImagesURL {
public enum Size: String {
case Original = "original"
case Size32 = "32px"
case Size40 = "40px"
case Size44 = "44px"
case Size48 = "48px"
case Size50 = "50px"
case Size60 = "60px"
case Size64 = "64px"
case Size73 = "73px"
case Size80 = "80px"
case Size88 = "88px"
case Size96 = "96px"
case Size100 = "100px"
case Size110 = "110px"
case Size120 = "120px"
case Size132 = "132px"
case Size146 = "146px"
case Size160 = "160px"
case Size176 = "176px"
case Size220 = "220px"
case Size264 = "264px"
case Size300 = "300px"
case Size850 = "850px"
case Retina32 = "32px@2X"
case Retina40 = "40px@2X"
case Retina44 = "44px@2X"
case Retina88 = "48px@2X"
case RetinaHD32 = "32px@3X"
case RetinaHD40 = "40px@3X"
case RetinaHD44 = "44px@3X"
case RetinaHD88 = "48px@3X"
}
let images: NSDictionary
/// All available sizes
public var sizes: [Size] {
var keys = [Size]()
for key in images.allKeys {
if let key = key as? String, let size = Size(rawValue: key) {
keys.append(size)
}
}
return keys
}
public init(dictionary: NSDictionary) {
images = dictionary
}
public subscript(key: Size) -> NSURL? {
get {
if let imageURL = images[key.rawValue] as? String {
return NSURL(string: imageURL)
} else {
return .None
}
}
}
}
| a241b3457a46712c98eff1eb972c76ce | 24.847222 | 73 | 0.506717 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Network/Sources/NetworkKit/General/Adapter/NetworkAdapter.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import Errors
import Foundation
import ToolKit
public final class NetworkAdapter: NetworkAdapterAPI {
private let communicator: NetworkCommunicatorAPI
public init(
communicator: NetworkCommunicatorAPI = resolve()
) {
self.communicator = communicator
}
public func performOptional<ResponseType: Decodable>(
request: NetworkRequest,
responseType: ResponseType.Type
) -> AnyPublisher<ResponseType?, NetworkError> {
communicator.dataTaskPublisher(for: request)
.decodeOptional(responseType: responseType, for: request, using: request.decoder)
.eraseToAnyPublisher()
}
public func performOptional<ResponseType: Decodable, ErrorResponseType: FromNetworkErrorConvertible>(
request: NetworkRequest,
responseType: ResponseType.Type
) -> AnyPublisher<ResponseType?, ErrorResponseType> {
communicator.dataTaskPublisher(for: request)
.decodeOptional(responseType: responseType, for: request, using: request.decoder)
.eraseToAnyPublisher()
}
public func perform<ResponseType: Decodable, ErrorResponseType: FromNetworkErrorConvertible>(
request: NetworkRequest
) -> AnyPublisher<ResponseType, ErrorResponseType> {
communicator.dataTaskPublisher(for: request)
.decode(for: request, using: request.decoder)
.eraseToAnyPublisher()
}
public func perform<ResponseType: Decodable>(
request: NetworkRequest
) -> AnyPublisher<ResponseType, NetworkError> {
communicator.dataTaskPublisher(for: request)
.decode(for: request, using: request.decoder)
.eraseToAnyPublisher()
}
public func performWebsocket<ResponseType: Decodable>(
request: NetworkRequest
) -> AnyPublisher<ResponseType, NetworkError> {
communicator
.dataTaskWebSocketPublisher(for: request)
.decode(
for: request,
using: request.decoder
)
.eraseToAnyPublisher()
}
}
extension AnyPublisher where Output == ServerResponse,
Failure == NetworkError
{
fileprivate func decodeOptional<ResponseType: Decodable>(
responseType: ResponseType.Type,
for request: NetworkRequest,
using decoder: NetworkResponseDecoderAPI
) -> AnyPublisher<ResponseType?, NetworkError> {
decodeOptionalSuccess(for: request, responseType: responseType, using: decoder)
}
fileprivate func decodeOptional<ResponseType: Decodable, ErrorResponseType: FromNetworkErrorConvertible>(
responseType: ResponseType.Type,
for request: NetworkRequest,
using decoder: NetworkResponseDecoderAPI
) -> AnyPublisher<ResponseType?, ErrorResponseType> {
decodeError(for: request, using: decoder)
.decodeOptionalSuccess(for: request, responseType: responseType, using: decoder)
}
fileprivate func decode<ResponseType: Decodable, ErrorResponseType: FromNetworkErrorConvertible>(
for request: NetworkRequest,
using decoder: NetworkResponseDecoderAPI
) -> AnyPublisher<ResponseType, ErrorResponseType> {
decodeError(for: request, using: decoder)
.decodeSuccess(for: request, using: decoder)
}
fileprivate func decode<ResponseType: Decodable>(
for request: NetworkRequest,
using decoder: NetworkResponseDecoderAPI
) -> AnyPublisher<ResponseType, NetworkError> {
decodeSuccess(for: request, using: decoder)
}
}
extension AnyPublisher where Output == ServerResponse,
Failure == NetworkError
{
fileprivate func decodeError<ErrorResponseType: FromNetworkErrorConvertible>(
for request: NetworkRequest,
using decoder: NetworkResponseDecoderAPI
) -> AnyPublisher<ServerResponse, ErrorResponseType> {
mapError { communicatorError -> ErrorResponseType in
decoder.decode(
error: communicatorError,
for: request
)
}
.eraseToAnyPublisher()
}
}
extension AnyPublisher where Output == ServerResponse,
Failure: FromNetworkErrorConvertible
{
fileprivate func decodeSuccess<ResponseType: Decodable>(
for request: NetworkRequest,
using decoder: NetworkResponseDecoderAPI
) -> AnyPublisher<ResponseType, Failure> {
flatMap { response -> AnyPublisher<ResponseType, Failure> in
decoder.decode(response: response, for: request).publisher.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
fileprivate func decodeOptionalSuccess<ResponseType: Decodable>(
for request: NetworkRequest,
responseType: ResponseType.Type,
using decoder: NetworkResponseDecoderAPI
) -> AnyPublisher<ResponseType?, Failure> {
flatMap { response -> AnyPublisher<ResponseType?, Failure> in
decoder
.decodeOptional(
response: response,
responseType: responseType,
for: request
)
.publisher.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
}
extension AnyPublisher where Output == ServerResponse,
Failure == NetworkError
{
fileprivate func decodeSuccess<ResponseType: Decodable>(
for request: NetworkRequest,
using decoder: NetworkResponseDecoderAPI
) -> AnyPublisher<ResponseType, NetworkError> {
flatMap { response -> AnyPublisher<ResponseType, NetworkError> in
decoder.decode(response: response, for: request).publisher.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
fileprivate func decodeOptionalSuccess<ResponseType: Decodable>(
for request: NetworkRequest,
responseType: ResponseType.Type,
using decoder: NetworkResponseDecoderAPI
) -> AnyPublisher<ResponseType?, NetworkError> {
flatMap { response -> AnyPublisher<ResponseType?, NetworkError> in
decoder
.decodeOptional(
response: response,
responseType: responseType,
for: request
)
.publisher.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
}
| c6214e9bac4866d145384a4867dd9e95 | 34.032787 | 109 | 0.668226 | false | false | false | false |
amosavian/swift-corelibs-foundation | refs/heads/master | Tools/plutil/main.swift | apache-2.0 | 10 | // 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
//
#if os(OSX) || os(iOS)
import Darwin
import SwiftFoundation
#elseif os(Linux)
import Foundation
import Glibc
#endif
func help() -> Int32 {
print("plutil: [command_option] [other_options] file...\n" +
"The file '-' means stdin\n" +
"Command options are (-lint is the default):\n" +
" -help show this message and exit\n" +
" -lint check the property list files for syntax errors\n" +
" -convert fmt rewrite property list files in format\n" +
" fmt is one of: xml1 binary1 json\n" +
" -p print property list in a human-readable fashion\n" +
" (not for machine parsing! this 'format' is not stable)\n" +
"There are some additional optional arguments that apply to -convert\n" +
" -s be silent on success\n" +
" -o path specify alternate file path name for result;\n" +
" the -o option is used with -convert, and is only\n" +
" useful with one file argument (last file overwrites);\n" +
" the path '-' means stdout\n" +
" -e extension specify alternate extension for converted files\n" +
" -r if writing JSON, output in human-readable form\n" +
" -- specifies that all further arguments are file names\n")
return EXIT_SUCCESS
}
enum ExecutionMode {
case help
case lint
case convert
case print
}
enum ConversionFormat {
case xml1
case binary1
case json
}
struct Options {
var mode: ExecutionMode = .lint
var silent: Bool = false
var output: String?
var fileExtension: String?
var humanReadable: Bool?
var conversionFormat: ConversionFormat?
var inputs = [String]()
}
enum OptionParseError : Swift.Error {
case unrecognizedArgument(String)
case missingArgument(String)
case invalidFormat(String)
}
func parseArguments(_ args: [String]) throws -> Options {
var opts = Options()
var iterator = args.makeIterator()
while let arg = iterator.next() {
switch arg {
case "--":
while let path = iterator.next() {
opts.inputs.append(path)
}
case "-s":
opts.silent = true
case "-o":
if let path = iterator.next() {
opts.output = path
} else {
throw OptionParseError.missingArgument("-o requires a path argument")
}
case "-convert":
opts.mode = .convert
if let format = iterator.next() {
switch format {
case "xml1":
opts.conversionFormat = .xml1
case "binary1":
opts.conversionFormat = .binary1
case "json":
opts.conversionFormat = .json
default:
throw OptionParseError.invalidFormat(format)
}
} else {
throw OptionParseError.missingArgument("-convert requires a format argument of xml1 binary1 json")
}
case "-e":
if let ext = iterator.next() {
opts.fileExtension = ext
} else {
throw OptionParseError.missingArgument("-e requires an extension argument")
}
case "-help":
opts.mode = .help
case "-lint":
opts.mode = .lint
case "-p":
opts.mode = .print
default:
if arg.hasPrefix("-") && arg.utf8.count > 1 {
throw OptionParseError.unrecognizedArgument(arg)
}
}
}
return opts
}
func lint(_ options: Options) -> Int32 {
if options.output != nil {
print("-o is not used with -lint")
let _ = help()
return EXIT_FAILURE
}
if options.fileExtension != nil {
print("-e is not used with -lint")
let _ = help()
return EXIT_FAILURE
}
if options.inputs.count < 1 {
print("No files specified.")
let _ = help()
return EXIT_FAILURE
}
let silent = options.silent
var doError = false
for file in options.inputs {
let data : Data?
if file == "-" {
// stdin
data = FileHandle.standardInput.readDataToEndOfFile()
} else {
data = try? Data(contentsOf: URL(fileURLWithPath: file))
}
if let d = data {
do {
let _ = try PropertyListSerialization.propertyList(from: d, options: [], format: nil)
if !silent {
print("\(file): OK")
}
} catch {
print("\(file): \(error)")
}
} else {
print("\(file) does not exists or is not readable or is not a regular file")
doError = true
continue
}
}
if doError {
return EXIT_FAILURE
} else {
return EXIT_SUCCESS
}
}
func convert(_ options: Options) -> Int32 {
print("Unimplemented")
return EXIT_FAILURE
}
enum DisplayType {
case primary
case key
case value
}
extension Dictionary {
func display(_ indent: Int = 0, type: DisplayType = .primary) {
let indentation = String(repeating: " ", count: indent * 2)
switch type {
case .primary, .key:
print("\(indentation)[\n", terminator: "")
case .value:
print("[\n", terminator: "")
}
forEach() {
if let key = $0.0 as? String {
key.display(indent + 1, type: .key)
} else {
fatalError("plists should have strings as keys but got a \(type(of: $0.0))")
}
print(" => ", terminator: "")
displayPlist($0.1, indent: indent + 1, type: .value)
}
print("\(indentation)]\n", terminator: "")
}
}
extension Array {
func display(_ indent: Int = 0, type: DisplayType = .primary) {
let indentation = String(repeating: " ", count: indent * 2)
switch type {
case .primary, .key:
print("\(indentation)[\n", terminator: "")
case .value:
print("[\n", terminator: "")
}
for idx in 0..<count {
print("\(indentation) \(idx) => ", terminator: "")
displayPlist(self[idx], indent: indent + 1, type: .value)
}
print("\(indentation)]\n", terminator: "")
}
}
extension String {
func display(_ indent: Int = 0, type: DisplayType = .primary) {
let indentation = String(repeating: " ", count: indent * 2)
switch type {
case .primary:
print("\(indentation)\"\(self)\"\n", terminator: "")
case .key:
print("\(indentation)\"\(self)\"", terminator: "")
case .value:
print("\"\(self)\"\n", terminator: "")
}
}
}
extension Bool {
func display(_ indent: Int = 0, type: DisplayType = .primary) {
let indentation = String(repeating: " ", count: indent * 2)
switch type {
case .primary:
print("\(indentation)\"\(self ? "1" : "0")\"\n", terminator: "")
case .key:
print("\(indentation)\"\(self ? "1" : "0")\"", terminator: "")
case .value:
print("\"\(self ? "1" : "0")\"\n", terminator: "")
}
}
}
extension NSNumber {
func display(_ indent: Int = 0, type: DisplayType = .primary) {
let indentation = String(repeating: " ", count: indent * 2)
switch type {
case .primary:
print("\(indentation)\"\(self)\"\n", terminator: "")
case .key:
print("\(indentation)\"\(self)\"", terminator: "")
case .value:
print("\"\(self)\"\n", terminator: "")
}
}
}
extension NSData {
func display(_ indent: Int = 0, type: DisplayType = .primary) {
let indentation = String(repeating: " ", count: indent * 2)
switch type {
case .primary:
print("\(indentation)\"\(self)\"\n", terminator: "")
case .key:
print("\(indentation)\"\(self)\"", terminator: "")
case .value:
print("\"\(self)\"\n", terminator: "")
}
}
}
func displayPlist(_ plist: Any, indent: Int = 0, type: DisplayType = .primary) {
switch plist {
case let val as [String : Any]:
val.display(indent, type: type)
case let val as [Any]:
val.display(indent, type: type)
case let val as String:
val.display(indent, type: type)
case let val as Bool:
val.display(indent, type: type)
case let val as NSNumber:
val.display(indent, type: type)
case let val as NSData:
val.display(indent, type: type)
default:
fatalError("unhandled type \(type(of: plist))")
}
}
func display(_ options: Options) -> Int32 {
if options.inputs.count < 1 {
print("No files specified.")
let _ = help()
return EXIT_FAILURE
}
var doError = false
for file in options.inputs {
let data : Data?
if file == "-" {
// stdin
data = FileHandle.standardInput.readDataToEndOfFile()
} else {
data = try? Data(contentsOf: URL(fileURLWithPath: file))
}
if let d = data {
do {
let plist = try PropertyListSerialization.propertyList(from: d, options: [], format: nil)
displayPlist(plist)
} catch {
print("\(file): \(error)")
}
} else {
print("\(file) does not exists or is not readable or is not a regular file")
doError = true
continue
}
}
if doError {
return EXIT_FAILURE
} else {
return EXIT_SUCCESS
}
}
func main() -> Int32 {
var args = ProcessInfo.processInfo.arguments
if args.count < 2 {
print("No files specified.")
return EXIT_FAILURE
}
// Throw away process path
args.removeFirst()
do {
let opts = try parseArguments(args)
switch opts.mode {
case .lint:
return lint(opts)
case .convert:
return convert(opts)
case .print:
return display(opts)
case .help:
return help()
}
} catch let err {
switch err as! OptionParseError {
case .unrecognizedArgument(let arg):
print("unrecognized option: \(arg)")
let _ = help()
case .invalidFormat(let format):
print("unrecognized format \(format)\nformat should be one of: xml1 binary1 json")
case .missingArgument(let errorStr):
print(errorStr)
}
return EXIT_FAILURE
}
}
exit(main())
| 3119830e4b0cda13a211a1b2efea687d | 29.664935 | 118 | 0.502033 | false | false | false | false |
Antondomashnev/Sourcery | refs/heads/master | Pods/XcodeEdit/Sources/Serialization.swift | mit | 1 | //
// Serialization.swift
// XcodeEdit
//
// Created by Tom Lokhorst on 2015-08-29.
// Copyright © 2015 nonstrict. All rights reserved.
//
import Foundation
extension XCProjectFile {
public func write(to url: URL, format: PropertyListSerialization.PropertyListFormat? = nil) throws {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
let name = try XCProjectFile.projectName(from: url)
let path = url.appendingPathComponent("project.pbxproj", isDirectory: false)
let serializer = Serializer(projectName: name, projectFile: self)
let plformat = format ?? self.format
if plformat == PropertyListSerialization.PropertyListFormat.openStep {
try serializer.openStepSerialization.write(to: path, atomically: true, encoding: String.Encoding.utf8)
}
else {
let data = try PropertyListSerialization.data(fromPropertyList: dict, format: plformat, options: 0)
try data.write(to: path)
}
}
public func serialized(projectName: String) throws -> Data {
let serializer = Serializer(projectName: projectName, projectFile: self)
if format == PropertyListSerialization.PropertyListFormat.openStep {
return serializer.openStepSerialization.data(using: String.Encoding.utf8)!
}
else {
return try PropertyListSerialization.data(fromPropertyList: dict, format: format, options: 0)
}
}
}
let nonescapeRegex = try! NSRegularExpression(pattern: "^[a-z0-9_\\$\\.\\/]+$", options: NSRegularExpression.Options.caseInsensitive)
let specialRegexes = [
"\\\\": try! NSRegularExpression(pattern: "\\\\", options: []),
"\\\"": try! NSRegularExpression(pattern: "\"", options: []),
"\\n": try! NSRegularExpression(pattern: "\\n", options: []),
"\\r": try! NSRegularExpression(pattern: "\\r", options: []),
"\\t": try! NSRegularExpression(pattern: "\\t", options: []),
]
internal class Serializer {
let projectName: String
let projectFile: XCProjectFile
init(projectName: String, projectFile: XCProjectFile) {
self.projectName = projectName
self.projectFile = projectFile
}
lazy var targetsByConfigId: [String: PBXNativeTarget] = {
var dict: [String: PBXNativeTarget] = [:]
for target in self.projectFile.project.targets {
dict[target.buildConfigurationList.id] = target
}
return dict
}()
lazy var buildPhaseByFileId: [String: PBXBuildPhase] = {
let buildPhases = self.projectFile.allObjects.dict.values.ofType(PBXBuildPhase.self)
var dict: [String: PBXBuildPhase] = [:]
for buildPhase in buildPhases {
for file in buildPhase.files {
dict[file.id] = buildPhase
}
}
return dict
}()
var openStepSerialization: String {
var lines = [
"// !$*UTF8*$!",
"{",
]
for key in projectFile.dict.keys.sorted() {
let val: AnyObject = projectFile.dict[key]!
if key == "objects" {
lines.append("\tobjects = {")
let groupedObjects = projectFile.allObjects.dict.values
.grouped { $0.isa }
.sorted { $0.0 }
for (isa, objects) in groupedObjects {
lines.append("")
lines.append("/* Begin \(isa) section */")
for object in objects.sorted(by: { $0.id }) {
let multiline = isa != "PBXBuildFile" && isa != "PBXFileReference"
let parts = rows(type: isa, objKey: object.id, multiline: multiline, dict: object.dict)
if multiline {
for ln in parts {
lines.append("\t\t" + ln)
}
}
else {
lines.append("\t\t" + parts.joined(separator: ""))
}
}
lines.append("/* End \(isa) section */")
}
lines.append("\t};")
}
else {
var comment = "";
if key == "rootObject" {
comment = " /* Project object */"
}
let row = "\(key) = \(val)\(comment);"
for line in row.components(separatedBy: "\n") {
lines.append("\t\(line)")
}
}
}
lines.append("}\n")
return lines.joined(separator: "\n")
}
func comment(forKey key: String) -> String? {
if key == projectFile.project.id {
return "Project object"
}
if let obj = projectFile.allObjects.dict[key] {
if let ref = obj as? PBXReference {
return ref.name ?? ref.path
}
if let target = obj as? PBXTarget {
return target.name
}
if let config = obj as? XCBuildConfiguration {
return config.name
}
if let copyFiles = obj as? PBXCopyFilesBuildPhase {
return copyFiles.name ?? "CopyFiles"
}
if obj is PBXFrameworksBuildPhase {
return "Frameworks"
}
if obj is PBXHeadersBuildPhase {
return "Headers"
}
if obj is PBXResourcesBuildPhase {
return "Resources"
}
if let shellScript = obj as? PBXShellScriptBuildPhase {
return shellScript.name ?? "ShellScript"
}
if obj is PBXSourcesBuildPhase {
return "Sources"
}
if let buildFile = obj as? PBXBuildFile {
if let buildPhase = buildPhaseByFileId[key],
let group = comment(forKey: buildPhase.id) {
if let fileRefId = buildFile.fileRef?.id {
if let fileRef = comment(forKey: fileRefId) {
return "\(fileRef) in \(group)"
}
}
else {
return "(null) in \(group)"
}
}
}
if obj is XCConfigurationList {
if let target = targetsByConfigId[key] {
return "Build configuration list for \(target.isa) \"\(target.name)\""
}
return "Build configuration list for PBXProject \"\(projectName)\""
}
return obj.isa
}
return nil
}
func valStr(_ val: String) -> String {
var str = val
for (replacement, regex) in specialRegexes {
let range = NSRange(location: 0, length: str.utf16.count)
let template = NSRegularExpression.escapedTemplate(for: replacement)
str = regex.stringByReplacingMatches(in: str, options: [], range: range, withTemplate: template)
}
let range = NSRange(location: 0, length: str.utf16.count)
if let _ = nonescapeRegex.firstMatch(in: str, options: [], range: range) {
return str
}
return "\"\(str)\""
}
func objval(key: String, val: AnyObject, multiline: Bool) -> [String] {
var parts: [String] = []
let keyStr = valStr(key)
if let valArr = val as? [String] {
parts.append("\(keyStr) = (")
var ps: [String] = []
for valItem in valArr {
let str = valStr(valItem)
var extraComment = ""
if let c = comment(forKey: valItem) {
extraComment = " /* \(c) */"
}
ps.append("\(str)\(extraComment),")
}
if multiline {
for p in ps {
parts.append("\t\(p)")
}
parts.append(");")
}
else {
parts.append(ps.map { $0 + " "}.joined(separator: "") + "); ")
}
}
else if let valArr = val as? [JsonObject] {
parts.append("\(keyStr) = (")
for valObj in valArr {
if multiline {
parts.append("\t{")
}
for valKey in valObj.keys.sorted() {
let valVal: AnyObject = valObj[valKey]!
let ps = objval(key: valKey, val: valVal, multiline: multiline)
if multiline {
for p in ps {
parts.append("\t\t\(p)")
}
}
else {
parts.append("\t" + ps.joined(separator: "") + "}; ")
}
}
if multiline {
parts.append("\t},")
}
}
parts.append(");")
}
else if let valObj = val as? JsonObject {
parts.append("\(keyStr) = {")
for valKey in valObj.keys.sorted() {
let valVal: AnyObject = valObj[valKey]!
let ps = objval(key: valKey, val: valVal, multiline: multiline)
if multiline {
for p in ps {
parts.append("\t\(p)")
}
}
else {
parts.append(ps.joined(separator: "") + "}; ")
}
}
if multiline {
parts.append("};")
}
}
else {
let str = valStr("\(val)")
var extraComment = "";
if let c = comment(forKey: str) {
extraComment = " /* \(c) */"
}
if key == "remoteGlobalIDString" || key == "TestTargetID" {
extraComment = ""
}
if multiline {
parts.append("\(keyStr) = \(str)\(extraComment);")
}
else {
parts.append("\(keyStr) = \(str)\(extraComment); ")
}
}
return parts
}
func rows(type: String, objKey: String, multiline: Bool, dict: JsonObject) -> [String] {
var parts: [String] = []
if multiline {
parts.append("isa = \(type);")
}
else {
parts.append("isa = \(type); ")
}
for key in dict.keys.sorted() {
if key == "isa" { continue }
let val: AnyObject = dict[key]!
for p in objval(key: key, val: val, multiline: multiline) {
parts.append(p)
}
}
var objComment = ""
if let c = comment(forKey: objKey) {
objComment = " /* \(c) */"
}
let opening = "\(objKey)\(objComment) = {"
let closing = "};"
if multiline {
var lines: [String] = []
lines.append(opening)
for part in parts {
lines.append("\t\(part)")
}
lines.append(closing)
return lines
}
else {
return [opening + parts.joined(separator: "") + closing]
}
}
}
| 0408e067580c57b71bdd5c542b56920d | 25.404372 | 133 | 0.561258 | false | false | false | false |
El-Fitz/ImageSlideshow | refs/heads/master | Pod/Classes/InputSources/KingfisherSource.swift | mit | 1 | //
// KingfisherSource.swift
// ImageSlideshow
//
// Created by feiin
//
//
import Kingfisher
public class KingfisherSource: NSObject, InputSource {
var url: URL
var placeholder: UIImage?
public init(url: URL) {
self.url = url
super.init()
}
public init(url: URL, placeholder: UIImage) {
self.url = url
self.placeholder = placeholder
super.init()
}
public init?(urlString: String) {
if let validUrl = URL(string: urlString) {
self.url = validUrl
super.init()
} else {
return nil
}
}
@objc public func load(to imageView: UIImageView, with callback: @escaping (UIImage) -> ()) {
imageView.kf.setImage(with: self.url, placeholder: self.placeholder, options: nil, progressBlock: nil) { (image, _, _, _) in
if let image = image {
callback(image)
}
}
}
}
| 6b1979ae0b2dfcc0c0ec2f63896fa8b0 | 22 | 132 | 0.550725 | false | false | false | false |
lukaszwas/mcommerce-api | refs/heads/master | Sources/App/Controllers/CategoryController.swift | mit | 1 | import Vapor
import HTTP
// /categories
final class CategoryController {
// Routes
func makeRoutes(routes: RouteBuilder) {
let group = routes.grouped("categories")
group.get(handler: getAllCategories)
group.get(Category.parameter, handler: getCategoryWithId)
group.post(handler: createCategory)
group.delete(Category.parameter, handler: deleteCategory)
group.patch(Category.parameter, handler: updateCategory)
group.get("root", handler: getRootCategories)
group.get(Category.parameter, "subcategories", handler: getSubategories)
}
// METHODS
// GET /
// Get all categories
func getAllCategories(req: Request) throws -> ResponseRepresentable {
return try Category.all().makeJSON()
}
// GET /:id
// Get category with id
func getCategoryWithId(req: Request) throws -> ResponseRepresentable {
let category = try req.parameters.next(Category.self)
return category
}
// POST /
// Create category
func createCategory(req: Request) throws -> ResponseRepresentable {
let category = try req.category()
try category.save()
return category
}
// DELETE /:id
// Delete category with id
func deleteCategory(req: Request) throws -> ResponseRepresentable {
let category = try req.parameters.next(Category.self)
try category.delete()
return Response(status: .ok)
}
// PATCH /:id
// Update category
func updateCategory(req: Request) throws -> ResponseRepresentable {
let category = try req.parameters.next(Category.self)
try category.update(for: req)
try category.save()
return category
}
// GET /root
// Get root categories
func getRootCategories(req: Request) throws -> ResponseRepresentable {
return try Category.makeQuery().filter(Category.parentIdKey, .equals, nil).all().makeJSON()
}
// GET /:id/subcategories
// Get subcategories
func getSubategories(req: Request) throws -> ResponseRepresentable {
let category = try req.parameters.next(Category.self)
return try Category.makeQuery().filter(Category.parentIdKey, .equals, category.id).all().makeJSON()
}
}
// Deserialize JSON
extension Request {
func category() throws -> Category {
guard let json = json else { throw Abort.badRequest }
return try Category(json: json)
}
}
extension CategoryController: EmptyInitializable { }
| 193b892bdd7aaa1f7d8b78b85451ad47 | 30.292683 | 107 | 0.651988 | false | false | false | false |
privacee/freelan-bar | refs/heads/master | xcode-swift/freelan-bar/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// freelan-bar
//
// Created by Andreas Streichardt on 12.12.14.
// Copyright (c) 2014 Andreas Streichardt. All rights reserved.
//
import Cocoa
import AppKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
//lazy var settingsWindowController = SettingsWindowController(windowNibName: "Settings")
var runner : UnisonRunner?
var unisonBar : UnisonBar?
var log : UnisonLog = UnisonLog()
func applicationWillFinishLaunching(aNotification: NSNotification?) {
NSApp.setActivationPolicy(NSApplicationActivationPolicy.Accessory)
}
func applicationDidFinishLaunching(aNotification: NSNotification?) {
unisonBar = UnisonBar(log: log)
runner = UnisonRunner(log: log)
let result = runner!.ensureRunning()
if (result != nil) {
let alert = NSAlert()
alert.addButtonWithTitle("Ok :(")
alert.messageText = "Got a fatal error: \(result!) :( Exiting"
alert.alertStyle = NSAlertStyle.WarningAlertStyle
let response = alert.runModal()
self.quit()
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: "tooManyErrors:", name: TooManyErrorsNotification, object: runner)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contactsDetermined:", name: ContactsDetermined, object: runner)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "httpChanged:", name: HttpChanged, object: runner)
}
func stop() {
runner?.stop()
}
func applicationWillTerminate(aNotification: NSNotification) {
// mop: i don't get it .... this will only get called when quitting via UI. SIGTERM will NOT land here and i fail installing a proper signal handler :|
self.stop()
}
func settingsAction(sender : AnyObject) {
//settingsWindowController.showWindow(sender)
}
func quitAction(sender : AnyObject) {
let alert = NSAlert()
alert.addButtonWithTitle("Yes")
alert.addButtonWithTitle("Cancel")
alert.messageText = "Are you sure you want to quit?"
alert.alertStyle = NSAlertStyle.WarningAlertStyle
let response = alert.runModal()
if (response == NSAlertFirstButtonReturn) {
self.quit()
}
}
func tooManyErrors(sender : AnyObject) {
let alert = NSAlert()
alert.addButtonWithTitle("Ok :(")
alert.messageText = "Freelan could not run. There were too many errors. Check log, and restart :("
alert.alertStyle = NSAlertStyle.WarningAlertStyle
let response = alert.runModal()
}
func httpChanged(notification: NSNotification) {
if let info = notification.userInfo {
var host = notification.userInfo!["host"] as! NSString
var port = notification.userInfo!["port"] as! NSString
freelanBar!.enableUIOpener("http://\(host):\(port)")
} else {
freelanBar!.disableUIOpener()
}
}
func contactsDetermined(notification: NSNotification) {
if let contacts = notification.userInfo!["contacts"] as? Array<FreelanContact> {
freelanBar!.setContacts(contacts)
}
}
func quit() {
NSApplication.sharedApplication().terminate(self)
}
}
| 0f01ab613d8f8294f6048d0aee35cb5e | 34.142857 | 159 | 0.642276 | false | false | false | false |
steryokhin/AsciiArtPlayer | refs/heads/master | src/AsciiArtPlayer/AsciiArtPlayerTests/Presentation/User Stories/Home/Assembly/HomeContainerTests.swift | mit | 1 | //
// HomeHomeContainerTests.swift
// AsciiArtPlayer
//
// Created by Sergey Teryokhin on 19/12/2016.
// Copyright © 2016 iMacDev. All rights reserved.
//
import XCTest
class HomeModuleConfiguratorTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testConfigureModuleForViewController() {
//given
let viewController = HomeViewControllerMock()
let configurator = HomeModuleConfigurator()
//when
configurator.configureModuleForViewInput(viewController)
//then
XCTAssertNotNil(viewController.output, "HomeViewController is nil after configuration")
XCTAssertTrue(viewController.output is HomePresenter, "output is not HomePresenter")
let presenter: HomePresenter = viewController.output as! HomePresenter
XCTAssertNotNil(presenter.view, "view in HomePresenter is nil after configuration")
XCTAssertNotNil(presenter.router, "router in HomePresenter is nil after configuration")
XCTAssertTrue(presenter.router is HomeRouter, "router is not HomeRouter")
let interactor: HomeInteractor = presenter.interactor as! HomeInteractor
XCTAssertNotNil(interactor.output, "output in HomeInteractor is nil after configuration")
}
class HomeViewControllerMock: HomeViewController {
var setupInitialStateDidCall = false
override func setupInitialState() {
setupInitialStateDidCall = true
}
}
}
| ab05cdd13e5c56767b2450a356a4c125 | 32.396226 | 111 | 0.70791 | false | true | false | false |
sanghapark/Vigorous | refs/heads/master | Vigorous/AnimatableOperation.swift | mit | 1 | //
// AsyncOperation.swift
// FeedableTest
//
// Created by ParkSangHa on 2017. 3. 18..
// Copyright © 2017년 sanghapark1021. All rights reserved.
//
import Foundation
protocol AnimatableOperationDelegate {
func didFinishAnimator(name: String, success: Bool)
}
class AnimatableOperation: AsyncOperation {
typealias Executable = ( @escaping (_ success: Bool)->() ) -> ()
var delegate: AnimatableOperationDelegate?
var animatables = [Animatable]()
var didCompleteCount = 0
init(animatable: Animatable) {
self.animatables.append(animatable)
}
init(animatables: [Animatable]) {
self.animatables = animatables
}
override func main() {
super.main()
for animatable in self.animatables {
animatable.delegate = self
DispatchQueue.main.async {
animatable.animate()
}
}
}
}
extension AnimatableOperation: AnimatableDelegate {
func completion(with success: Bool) {
didCompleteCount += 1
if didCompleteCount >= self.animatables.count {
self.state = .Finished
self.delegate?.didFinishAnimator(name: self.name!, success: success)
}
}
}
| f1b0bc92d0c697c2691c2b259346328e | 20.660377 | 74 | 0.678571 | false | false | false | false |
InderKumarRathore/DeviceGuru | refs/heads/master | Sources/DeviceGuruImplementation.swift | mit | 1 | // Copyright @DeviceGuru
// Hardware string can be found @ https://www.everymac.com
import Foundation
public enum DeviceGuruException: Error {
case deviceNotPresentInThePlist(String)
case unableToCreateDeviceVersion(String)
}
public final class DeviceGuruImplementation: DeviceGuru {
private enum LocalStorageKeys {
static let hardwareDetail = "github.com/InderKumarRathore/DeviceGuru.HardwareDetail.Key"
static let deviceGuruVersion = "github.com/InderKumarRathore/DeviceGuru.Version.Key"
}
private lazy var hardwareDetail: [String: Any]? = {
guard let hardwareDetail = loadHardwareDetailFromUserDefaultsIfLatest() else {
let allDevices = loadAllDeviceDictionaryFromPlist()
let hardwareDetail = allDevices[_hardwareString] as? [String: Any]
saveHardwareDetailToUserDefaults(hardwareDetail: hardwareDetail)
return hardwareDetail
}
return hardwareDetail
}()
private lazy var _hardwareString: String = {
hardwareDetailProvider.hardwareString
}()
private let localStorage: LocalStorage
private let hardwareDetailProvider: HardwareDetailProvider
private let plistPath: String?
/// Initializes the DeviceGuru
/// - Parameters:
/// - localStorage: Provide any local storage where you want to save data related to the device, by default it uses `UserDefaults`
/// - plistPath: Provide plist file path, if passed nil it will search for appropriate bundles and load it for you.
public init(localStorage: LocalStorage = UserDefaults.standard,
hardwareDetailProvider: HardwareDetailProvider = HardwareDetailProviderImplementation(),
plistPath: String? = nil) {
self.localStorage = localStorage
self.hardwareDetailProvider = hardwareDetailProvider
self.plistPath = plistPath
}
public var hardwareString: String { _hardwareString }
public var platform: Platform {
let hardware = hardwareString
if (hardware.hasPrefix("iPhone")) { return .iPhone }
if (hardware.hasPrefix("iPod")) { return .iPodTouch }
if (hardware.hasPrefix("iPad")) { return .iPad }
if (hardware.hasPrefix("Watch")) { return .appleWatch }
if (hardware.hasPrefix("AppleTV")) { return .appleTV }
return .unknown
}
public func hardwareSimpleDescription() throws -> String {
let hardwareDescriptionString = try hardwareDescription()
// this expression matches all strings between round brackets (e.g (Wifi), (GSM)) except the pattern "[0-9]+ Gen"
let regEx = try NSRegularExpression(pattern: "\\((?![0-9]+ Gen).*\\)", options: .caseInsensitive)
let simpleName = regEx.stringByReplacingMatches(in: hardwareDescriptionString,
options: .init(rawValue: 0),
range: NSRange(location: 0, length: hardwareDescriptionString.count),
withTemplate: "")
return simpleName.trimmingCharacters(in: .whitespaces)
}
public func hardwareDescription() throws -> String {
if let hardwareDescription = hardwareDetail?["name"] as? String {
return hardwareDescription
}
//log message that your device is not present in the list
logMessage(hardwareString)
throw DeviceGuruException.deviceNotPresentInThePlist(hardwareString)
}
public func deviceVersion() throws -> DeviceVersion {
guard let versionString = findMatch(for: "[\\d]*,[\\d]*", in: hardwareString),
let version = getVersion(from: versionString) else {
print("Can't create Version from: \(hardwareString)")
print("Please report the above log to: https://github.com/InderKumarRathore/DeviceGuru")
throw DeviceGuruException.unableToCreateDeviceVersion(hardwareString)
}
return version
}
/// Internal method for loggin, you don't need this method
///
/// - parameters:
/// - hardware: `String` hardware type of the device
///
func logMessage(_ hardware: String) {
print("""
This is a device which is not listed in this library. Please visit https://github.com/InderKumarRathore/DeviceGuru and submit the issue there.\n
Your device hardware string is|\(hardware)|"
""")
}
}
// MARK: - Private Static methods
private extension DeviceGuruImplementation {
func findMatch(for regex: String, in text: String) -> String? {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text, range: NSRange(text.startIndex..., in: text))
return results.compactMap {
guard let range = Range($0.range, in: text) else {
print("Unable to create the range for: \(text)")
return nil
}
return String(text[range])
}.first
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return nil
}
}
func getVersion(from string: String) -> DeviceVersion? {
let components = string.components(separatedBy: ",")
guard components.count == 2 else {
print("Can't create components of string: \(string)")
return nil
}
let majorString = components[0].trimmingCharacters(in: .whitespacesAndNewlines)
let minorString = components[1].trimmingCharacters(in: .whitespacesAndNewlines)
guard let major = Int(majorString), let minor = Int(minorString) else {
print("Can't create major: \(majorString) and minor: \(minorString)")
return nil
}
return DeviceVersion(major: major, minor: minor)
}
func loadHardwareDetailFromUserDefaultsIfLatest() -> [String: Any]? {
let libraryVersion = localStorage.object(forKey: LocalStorageKeys.deviceGuruVersion) as? String
guard libraryVersion == Self.libraryVersion else { return nil }
return localStorage.object(forKey: LocalStorageKeys.hardwareDetail) as? [String: Any]
}
func saveHardwareDetailToUserDefaults(hardwareDetail: [String: Any]?) {
localStorage.setValue(Self.libraryVersion, forKey: LocalStorageKeys.deviceGuruVersion)
localStorage.setValue(hardwareDetail, forKey: LocalStorageKeys.hardwareDetail)
}
func loadAllDeviceDictionaryFromPlist() -> [String: AnyObject] {
if let plistPath = plistPath {
return loadDeviceDictionary(fromPath: plistPath)
}
if let dictionary = loadDeviceDictionaryFromTopBundle() {
return dictionary
}
if let dictionary = loadDeviceDictionaryFromMainBundle() {
return dictionary
}
if let dictionary = loadDeviceDictionaryFromFrameworkBundle() {
return dictionary
}
if let dictionary = loadDeviceDictionaryFromSwiftPackage() {
return dictionary
}
assertionFailure("Unable to find \(Constants.plistFileName).\(Constants.plistFileType)")
return [:]
}
func loadDeviceDictionary(fromPath path: String) -> [String: AnyObject] {
guard let dictionary = NSDictionary(contentsOfFile: path) as? [String: AnyObject] else {
assertionFailure("Plist is malformed")
return [:]
}
return dictionary
}
func loadDeviceDictionaryFromTopBundle() -> [String: AnyObject]? {
let topBundle = Bundle(for: type(of: self))
guard let url = topBundle.url(forResource: "DeviceGuru", withExtension: "bundle"),
let bundle = Bundle(url: url) else {
// Bundle not found
return nil
}
guard let path = bundle.path(forResource: Constants.plistFileName, ofType: Constants.plistFileType),
let dictionary = NSDictionary(contentsOfFile: path) as? [String: AnyObject] else {
assertionFailure("DeviceList.plist not found in the bundle.")
return nil
}
return dictionary
}
func loadDeviceDictionaryFromFrameworkBundle() -> [String: AnyObject]? {
let bundle = Bundle(for: type(of: self))
guard let path = bundle.path(forResource: Constants.plistFileName, ofType: Constants.plistFileType),
let dictionary = NSDictionary(contentsOfFile: path) as? [String: AnyObject] else {
return nil
}
return dictionary
}
func loadDeviceDictionaryFromMainBundle() -> [String: AnyObject]? {
guard let path = Bundle.main.path(forResource: Constants.plistFileName, ofType: Constants.plistFileType),
let dictionary = NSDictionary(contentsOfFile: path) as? [String: AnyObject] else {
return nil
}
return dictionary
}
func loadDeviceDictionaryFromSwiftPackage() -> [String: AnyObject]? {
#if SWIFT_PACKAGE
let resource = "DeviceList"
let type = "plist"
guard let path = Bundle.module.path(forResource: resource, ofType: type),
let dictionary = NSDictionary(contentsOfFile: path) as? [String: AnyObject] else {
return nil
}
return dictionary
#else
return nil
#endif
}
}
// Mark:- Private UserDefaults
extension UserDefaults: LocalStorage {}
private enum Constants {
static let plistFileName = "DeviceList"
static let plistFileType = "plist"
}
| 9199f08fbc1913b383b02af694653e6c | 38.455285 | 156 | 0.639604 | false | false | false | false |
jasonwedepohl/udacity-ios-on-the-map | refs/heads/master | On The Map/On The Map/LocationFinder.swift | mit | 1 | //
// LocationFinder.swift
// On The Map
//
// Created by Jason Wedepohl on 2017/09/22.
//
import CoreLocation
class LocationFinder {
static func find(_ searchString: String, _ findCompletion: @escaping (_ coordinate: CLLocationCoordinate2D?) -> Void) {
CLGeocoder().geocodeAddressString(searchString, completionHandler: { (placemarks, error) in
if error != nil {
print(error!.localizedDescription)
findCompletion(nil)
return
}
if placemarks == nil || placemarks!.count == 0 {
findCompletion(nil)
return
}
guard let coordinate = placemarks![0].location?.coordinate else {
findCompletion(nil)
return
}
print("Coordinate: \(coordinate.latitude), \(coordinate.longitude)")
findCompletion(coordinate)
})
}
}
| 66421e4ea1839fa5cd12fa6458feaa9c | 22.606061 | 120 | 0.679076 | false | false | false | false |
Johnykutty/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Rules/ExplicitInitRule.swift | mit | 1 | //
// ExplicitInitRule.swift
// SwiftLint
//
// Created by Matt Taube on 7/2/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct ExplicitInitRule: ASTRule, ConfigurationProviderRule, CorrectableRule, OptInRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "explicit_init",
name: "Explicit Init",
description: "Explicitly calling .init() should be avoided.",
nonTriggeringExamples: [
"import Foundation; class C: NSObject { override init() { super.init() }}", // super
"struct S { let n: Int }; extension S { init() { self.init(n: 1) } }", // self
"[1].flatMap(String.init)", // pass init as closure
"[String.self].map { $0.init(1) }", // initialize from a metatype value
"[String.self].map { type in type.init(1) }" // initialize from a metatype value
],
triggeringExamples: [
"[1].flatMap{String↓.init($0)}",
"[String.self].map { Type in Type↓.init(1) }" // starting with capital assumes as type
],
corrections: [
"[1].flatMap{String↓.init($0)}": "[1].flatMap{String($0)}"
]
)
public func validate(file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
return violationRanges(in: file, kind: kind, dictionary: dictionary).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
private let initializerWithType = regex("^[A-Z].*\\.init$")
private func violationRanges(in file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [NSRange] {
func isExpected(_ name: String) -> Bool {
let range = NSRange(location: 0, length: name.utf16.count)
return !["super.init", "self.init"].contains(name)
&& initializerWithType.numberOfMatches(in: name, options: [], range: range) != 0
}
let length = ".init".utf8.count
guard kind == .call,
let name = dictionary.name, isExpected(name),
let nameOffset = dictionary.nameOffset,
let nameLength = dictionary.nameLength,
let range = file.contents.bridge()
.byteRangeToNSRange(start: nameOffset + nameLength - length, length: length)
else { return [] }
return [range]
}
private func violationRanges(in file: File, dictionary: [String: SourceKitRepresentable]) -> [NSRange] {
return dictionary.substructure.flatMap { subDict -> [NSRange] in
guard let kindString = subDict.kind,
let kind = SwiftExpressionKind(rawValue: kindString) else {
return []
}
return violationRanges(in: file, dictionary: subDict) +
violationRanges(in: file, kind: kind, dictionary: subDict)
}
}
private func violationRanges(in file: File) -> [NSRange] {
return violationRanges(in: file, dictionary: file.structure.dictionary).sorted { lh, rh in
lh.location > rh.location
}
}
public func correct(file: File) -> [Correction] {
let matches = violationRanges(in: file)
.filter { !file.ruleEnabled(violatingRanges: [$0], for: self).isEmpty }
guard !matches.isEmpty else { return [] }
let description = type(of: self).description
var corrections = [Correction]()
var contents = file.contents
for range in matches {
contents = contents.bridge().replacingCharacters(in: range, with: "")
let location = Location(file: file, characterOffset: range.location)
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(contents)
return corrections
}
}
| bb5e2b6fb7a276ae80c9eb919d05ec6c | 40.145631 | 108 | 0.59816 | false | false | false | false |
shahmishal/swift | refs/heads/master | test/Sema/accessibility.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -enable-objc-interop -disable-objc-attr-requires-foundation-module -swift-version 5
public protocol PublicProto {
func publicReq()
}
// expected-note@+1 * {{type declared here}}
internal protocol InternalProto {
func internalReq()
}
fileprivate protocol FilePrivateProto {
func filePrivateReq()
}
// expected-note@+1 * {{type declared here}}
private protocol PrivateProto {
func privateReq()
}
public struct PublicStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'public' to satisfy the requirement}} {{3-10=public}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-10=internal}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
public var publicVar = 0
}
// expected-note@+1 * {{type declared here}}
internal struct InternalStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-10=internal}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-10=internal}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
public var publicVar = 0
}
// expected-note@+1 * {{type declared here}}
fileprivate struct FilePrivateStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
public var publicVar = 0
}
// expected-note@+1 * {{type declared here}}
private struct PrivateStruct: PublicProto, InternalProto, FilePrivateProto, PrivateProto {
private func publicReq() {} // expected-error {{method 'publicReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func internalReq() {} // expected-error {{method 'internalReq()' must be as accessible as its enclosing type because it matches a requirement in protocol 'InternalProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func filePrivateReq() {} // expected-error {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func privateReq() {} // expected-error {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}} expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
public var publicVar = 0
}
public struct PublicStructWithInternalExtension: PublicProto, InternalProto, FilePrivateProto, PrivateProto {}
// expected-error@-1 {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{none}}
// expected-error@-2 {{method 'internalReq()' must be declared internal because it matches a requirement in internal protocol 'InternalProto'}} {{none}}
// expected-error@-3 {{method 'filePrivateReq()' must be declared fileprivate because it matches a requirement in fileprivate protocol 'FilePrivateProto'}} {{none}}
// expected-error@-4 {{method 'privateReq()' must be declared fileprivate because it matches a requirement in private protocol 'PrivateProto'}} {{none}}
internal extension PublicStructWithInternalExtension {
private func publicReq() {} // expected-note {{move the instance method to another extension where it can be declared 'public' to satisfy the requirement}} {{none}}
private func internalReq() {} // expected-note {{mark the instance method as 'internal' to satisfy the requirement}} {{3-11=}}
private func filePrivateReq() {} // expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
private func privateReq() {} // expected-note {{mark the instance method as 'fileprivate' to satisfy the requirement}} {{3-10=fileprivate}}
}
extension PublicStruct {
public init(x: Int) { self.init() }
}
extension InternalStruct {
public init(x: Int) { self.init() }
}
extension FilePrivateStruct {
public init(x: Int) { self.init() }
}
extension PrivateStruct {
public init(x: Int) { self.init() }
}
public extension PublicStruct {
public func extMemberPublic() {} // expected-warning {{'public' modifier is redundant for instance method declared in a public extension}} {{3-10=}}
fileprivate func extFuncPublic() {}
private func extImplPublic() {}
}
internal extension PublicStruct {
public func extMemberInternal() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'internal'}} {{none}}
fileprivate func extFuncInternal() {}
private func extImplInternal() {}
}
fileprivate extension PublicStruct {
public func extMemberFilePrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'fileprivate'}} {{none}}
fileprivate func extFuncFilePrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a fileprivate extension}} {{3-15=}}
private func extImplFilePrivate() {}
}
private extension PublicStruct {
public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}}
fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}}
private func extImplPrivate() {}
}
public extension InternalStruct { // expected-error {{extension of internal struct cannot be declared public}} {{1-8=}}
public func extMemberPublic() {} // expected-warning {{'public' modifier is redundant for instance method declared in a public extension}} {{3-10=}}
fileprivate func extFuncPublic() {}
private func extImplPublic() {}
}
internal extension InternalStruct {
public func extMemberInternal() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'internal'}} {{none}}
fileprivate func extFuncInternal() {}
private func extImplInternal() {}
}
fileprivate extension InternalStruct {
public func extMemberFilePrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'fileprivate'}} {{none}}
fileprivate func extFuncFilePrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a fileprivate extension}} {{3-15=}}
private func extImplFilePrivate() {}
}
private extension InternalStruct {
public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}}
fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}}
private func extImplPrivate() {}
}
public extension FilePrivateStruct { // expected-error {{extension of fileprivate struct cannot be declared public}} {{1-8=}}
public func extMemberPublic() {} // expected-warning {{'public' modifier is redundant for instance method declared in a public extension}} {{3-10=}}
fileprivate func extFuncPublic() {}
private func extImplPublic() {}
}
internal extension FilePrivateStruct { // expected-error {{extension of fileprivate struct cannot be declared internal}} {{1-10=}}
public func extMemberInternal() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'internal'}} {{none}}
fileprivate func extFuncInternal() {}
private func extImplInternal() {}
}
fileprivate extension FilePrivateStruct {
public func extMemberFilePrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'fileprivate'}} {{none}}
fileprivate func extFuncFilePrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a fileprivate extension}} {{3-15=}}
private func extImplFilePrivate() {}
}
private extension FilePrivateStruct {
public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}}
fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}}
private func extImplPrivate() {}
}
public extension PrivateStruct { // expected-error {{extension of private struct cannot be declared public}} {{1-8=}}
public func extMemberPublic() {} // expected-warning {{'public' modifier is redundant for instance method declared in a public extension}} {{3-10=}}
fileprivate func extFuncPublic() {}
private func extImplPublic() {}
}
internal extension PrivateStruct { // expected-error {{extension of private struct cannot be declared internal}} {{1-10=}}
public func extMemberInternal() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'internal'}} {{none}}
fileprivate func extFuncInternal() {}
private func extImplInternal() {}
}
fileprivate extension PrivateStruct { // expected-error {{extension of private struct cannot be declared fileprivate}} {{1-13=}}
public func extMemberFilePrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'fileprivate'}} {{none}}
fileprivate func extFuncFilePrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a fileprivate extension}} {{3-15=}}
private func extImplFilePrivate() {}
}
private extension PrivateStruct {
public func extMemberPrivate() {} // expected-warning {{'public' modifier conflicts with extension's default access of 'private'}} {{none}}
fileprivate func extFuncPrivate() {} // expected-warning {{'fileprivate' modifier is redundant for instance method declared in a private (equivalent to fileprivate) extension}} {{3-15=}}
private func extImplPrivate() {}
}
public struct PublicStructDefaultMethods: PublicProto, InternalProto, PrivateProto {
func publicReq() {} // expected-error {{method 'publicReq()' must be declared public because it matches a requirement in public protocol 'PublicProto'}} {{none}} expected-note {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }}
func internalReq() {}
func privateReq() {}
}
public class Base {
required public init() {}
// expected-note@+1 * {{overridden declaration is here}}
public func foo() {}
// expected-note@+1 * {{overridden declaration is here}}
public internal(set) var bar: Int = 0
// expected-note@+1 * {{overridden declaration is here}}
public subscript () -> () { return () }
}
public extension Base {
open func extMemberPublic() {} // expected-warning {{'open' modifier conflicts with extension's default access of 'public'}}
}
internal extension Base {
open func extMemberInternal() {} // expected-warning {{'open' modifier conflicts with extension's default access of 'internal'}}
}
public class PublicSub: Base {
private required init() {} // expected-error {{'required' initializer must be accessible wherever class 'PublicSub' can be subclassed}} {{3-10=internal}}
override func foo() {} // expected-error {{overriding instance method must be as accessible as the declaration it overrides}} {{3-3=public }}
override var bar: Int { // expected-error {{overriding property must be as accessible as the declaration it overrides}} {{3-3=public }}
get { return 0 }
set {}
}
override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as the declaration it overrides}} {{3-3=public }}
}
public class PublicSubGood: Base {
required init() {} // okay
}
internal class InternalSub: Base {
required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'InternalSub' can be subclassed}} {{12-19=internal}}
private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=internal}}
private override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=internal}}
get { return 0 }
set {}
}
private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=internal}}
}
internal class InternalSubGood: Base {
required init() {} // no-warning
override func foo() {}
override var bar: Int {
get { return 0 }
set {}
}
override subscript () -> () { return () }
}
internal class InternalSubPrivateSet: Base {
required init() {}
private(set) override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-16=}}
get { return 0 }
set {}
}
private(set) override subscript () -> () { // okay; read-only in base class
get { return () }
set {}
}
}
fileprivate class FilePrivateSub: Base {
required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'FilePrivateSub' can be subclassed}} {{12-19=fileprivate}}
private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=fileprivate}}
private override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=fileprivate}}
get { return 0 }
set {}
}
private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=fileprivate}}
}
fileprivate class FilePrivateSubGood: Base {
required init() {} // no-warning
override func foo() {}
override var bar: Int {
get { return 0 }
set {}
}
override subscript () -> () { return () }
}
fileprivate class FilePrivateSubGood2: Base {
fileprivate required init() {} // no-warning
fileprivate override func foo() {}
fileprivate override var bar: Int {
get { return 0 }
set {}
}
fileprivate override subscript () -> () { return () }
}
fileprivate class FilePrivateSubPrivateSet: Base {
required init() {}
private(set) override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=fileprivate}}
get { return 0 }
set {}
}
private(set) override subscript () -> () { // okay; read-only in base class
get { return () }
set {}
}
}
private class PrivateSub: Base {
required private init() {} // expected-error {{'required' initializer must be accessible wherever class 'PrivateSub' can be subclassed}} {{12-19=fileprivate}}
private override func foo() {} // expected-error {{overriding instance method must be as accessible as its enclosing type}} {{3-10=fileprivate}}
private override var bar: Int { // expected-error {{overriding property must be as accessible as its enclosing type}} {{3-10=fileprivate}}
get { return 0 }
set {}
}
private override subscript () -> () { return () } // expected-error {{overriding subscript must be as accessible as its enclosing type}} {{3-10=fileprivate}}
}
private class PrivateSubGood: Base {
required fileprivate init() {}
fileprivate override func foo() {}
fileprivate override var bar: Int {
get { return 0 }
set {}
}
fileprivate override subscript () -> () { return () }
}
private class PrivateSubPrivateSet: Base {
required fileprivate init() {}
fileprivate override func foo() {}
private(set) override var bar: Int { // expected-error {{setter of overriding property must be as accessible as its enclosing type}}
get { return 0 }
set {}
}
private(set) override subscript () -> () { // okay; read-only in base class
get { return () }
set {}
}
}
public typealias PublicTA1 = PublicStruct
public typealias PublicTA2 = InternalStruct // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias PublicTA3 = FilePrivateStruct // expected-error {{type alias cannot be declared public because its underlying type uses a fileprivate type}}
public typealias PublicTA4 = PrivateStruct // expected-error {{type alias cannot be declared public because its underlying type uses a private type}}
// expected-note@+1 {{type declared here}}
internal typealias InternalTA1 = PublicStruct
internal typealias InternalTA2 = InternalStruct
internal typealias InternalTA3 = FilePrivateStruct // expected-error {{type alias cannot be declared internal because its underlying type uses a fileprivate type}}
internal typealias InternalTA4 = PrivateStruct // expected-error {{type alias cannot be declared internal because its underlying type uses a private type}}
public typealias PublicFromInternal = InternalTA1 // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
typealias FunctionType1 = (PrivateStruct) -> PublicStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias FunctionType2 = (PublicStruct) -> PrivateStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias FunctionType3 = (PrivateStruct) -> PrivateStruct // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias ArrayType = [PrivateStruct] // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias DictType = [String : PrivateStruct] // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
typealias GenericArgs = Optional<PrivateStruct> // expected-error {{type alias must be declared private or fileprivate because its underlying type uses a private type}}
public protocol HasAssocType {
associatedtype Inferred
func test(input: Inferred)
}
public struct AssocTypeImpl: HasAssocType {
public func test(input: Bool) {}
}
public let _: AssocTypeImpl.Inferred?
public let x: PrivateStruct = PrivateStruct() // expected-error {{constant cannot be declared public because its type uses a private type}}
public var a: PrivateStruct?, b: PrivateStruct? // expected-error 2 {{variable cannot be declared public because its type uses a private type}}
public var (c, d): (PrivateStruct?, PrivateStruct?) // expected-error {{variable cannot be declared public because its type uses a private type}}
var internalVar: PrivateStruct? // expected-error {{variable must be declared private or fileprivate because its type uses a private type}}
let internalConstant = PrivateStruct() // expected-error {{constant must be declared private or fileprivate because its type 'PrivateStruct' uses a private type}}
public let publicConstant = [InternalStruct]() // expected-error {{constant cannot be declared public because its type '[InternalStruct]' uses an internal type}}
public struct Properties {
public let x: PrivateStruct = PrivateStruct() // expected-error {{property cannot be declared public because its type uses a private type}}
public var a: PrivateStruct?, b: PrivateStruct? // expected-error 2 {{property cannot be declared public because its type uses a private type}}
public var (c, d): (PrivateStruct?, PrivateStruct?) // expected-error {{property cannot be declared public because its type uses a private type}}
let y = PrivateStruct() // expected-error {{property must be declared fileprivate because its type 'PrivateStruct' uses a private type}}
}
public struct Subscripts {
subscript (a: PrivateStruct) -> Int { return 0 } // expected-error {{subscript must be declared fileprivate because its index uses a private type}}
subscript (a: Int) -> PrivateStruct { return PrivateStruct() } // expected-error {{subscript must be declared fileprivate because its element type uses a private type}}
public subscript (a: PrivateStruct, b: Int) -> Int { return 0 } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: Int, b: PrivateStruct) -> Int { return 0 } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: InternalStruct, b: PrivateStruct) -> InternalStruct { return InternalStruct() } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: PrivateStruct, b: InternalStruct) -> PrivateStruct { return PrivateStruct() } // expected-error {{subscript cannot be declared public because its index uses a private type}}
public subscript (a: Int, b: Int) -> InternalStruct { return InternalStruct() } // expected-error {{subscript cannot be declared public because its element type uses an internal type}}
}
public struct Methods {
func foo(a: PrivateStruct) -> Int { return 0 } // expected-error {{method must be declared fileprivate because its parameter uses a private type}}
func bar(a: Int) -> PrivateStruct { return PrivateStruct() } // expected-error {{method must be declared fileprivate because its result uses a private type}}
public func a(a: PrivateStruct, b: Int) -> Int { return 0 } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func b(a: Int, b: PrivateStruct) -> Int { return 0 } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func c(a: InternalStruct, b: PrivateStruct) -> InternalStruct { return InternalStruct() } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func d(a: PrivateStruct, b: InternalStruct) -> PrivateStruct { return PrivateStruct() } // expected-error {{method cannot be declared public because its parameter uses a private type}}
public func e(a: Int, b: Int) -> InternalStruct { return InternalStruct() } // expected-error {{method cannot be declared public because its result uses an internal type}}
}
func privateParam(a: PrivateStruct) {} // expected-error {{function must be declared private or fileprivate because its parameter uses a private type}}
public struct Initializers {
init(a: PrivateStruct) {} // expected-error {{initializer must be declared fileprivate because its parameter uses a private type}}
public init(a: PrivateStruct, b: Int) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
public init(a: Int, b: PrivateStruct) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
public init(a: InternalStruct, b: PrivateStruct) {} // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
public init(a: PrivateStruct, b: InternalStruct) { } // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
}
public class PublicClass {}
// expected-note@+2 * {{type declared here}}
// expected-note@+1 * {{superclass is declared here}}
internal class InternalClass {}
// expected-note@+1 * {{type declared here}}
private class PrivateClass {}
public protocol AssocTypes {
associatedtype Foo
associatedtype Internal: InternalClass // expected-error {{associated type in a public protocol uses an internal type in its requirement}}
associatedtype InternalConformer: InternalProto // expected-error {{associated type in a public protocol uses an internal type in its requirement}}
associatedtype PrivateConformer: PrivateProto // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PI: PrivateProto, InternalProto // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype IP: InternalProto, PrivateProto // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PrivateDefault = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its default definition}}
associatedtype PublicDefault = PublicStruct
associatedtype PrivateDefaultConformer: PublicProto = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its default definition}}
associatedtype PublicDefaultConformer: PrivateProto = PublicStruct // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PrivatePrivateDefaultConformer: PrivateProto = PrivateStruct // expected-error {{associated type in a public protocol uses a private type in its requirement}}
associatedtype PublicPublicDefaultConformer: PublicProto = PublicStruct
}
public protocol RequirementTypes {
var x: PrivateStruct { get } // expected-error {{property cannot be declared public because its type uses a private type}}
subscript(x: Int) -> InternalStruct { get set } // expected-error {{subscript cannot be declared public because its element type uses an internal type}}
func foo() -> PrivateStruct // expected-error {{method cannot be declared public because its result uses a private type}}
init(x: PrivateStruct) // expected-error {{initializer cannot be declared public because its parameter uses a private type}}
}
protocol DefaultRefinesPrivate : PrivateProto {} // expected-error {{protocol must be declared private or fileprivate because it refines a private protocol}}
public protocol PublicRefinesPrivate : PrivateProto {} // expected-error {{public protocol cannot refine a private protocol}}
public protocol PublicRefinesInternal : InternalProto {} // expected-error {{public protocol cannot refine an internal protocol}}
public protocol PublicRefinesPI : PrivateProto, InternalProto {} // expected-error {{public protocol cannot refine a private protocol}}
public protocol PublicRefinesIP : InternalProto, PrivateProto {} // expected-error {{public protocol cannot refine a private protocol}}
// expected-note@+1 * {{type declared here}}
private typealias PrivateInt = Int
enum DefaultRawPrivate : PrivateInt { // expected-error {{enum must be declared private or fileprivate because its raw type uses a private type}}
case A
}
// Note: fileprivate is the most visible valid access level for
// Outer.DefaultRawPrivate, so the diagnostic should say that.
class Outer {
enum DefaultRawPrivate : PrivateInt { // expected-error {{enum must be declared fileprivate because its raw type uses a private type}}
case A
}
}
public enum PublicRawPrivate : PrivateInt { // expected-error {{enum cannot be declared public because its raw type uses a private type}}
case A
}
public enum MultipleConformance : PrivateProto, PrivateInt { // expected-error {{enum cannot be declared public because its raw type uses a private type}} expected-error {{must appear first}} {{35-35=PrivateInt, }} {{47-59=}}
case A
func privateReq() {}
}
open class OpenSubclassInternal : InternalClass {} // expected-error {{class cannot be declared open because its superclass is internal}} expected-error {{superclass 'InternalClass' of open class must be open}}
public class PublicSubclassPublic : PublicClass {}
public class PublicSubclassInternal : InternalClass {} // expected-error {{class cannot be declared public because its superclass is internal}}
public class PublicSubclassPrivate : PrivateClass {} // expected-error {{class cannot be declared public because its superclass is private}}
class DefaultSubclassPublic : PublicClass {}
class DefaultSubclassInternal : InternalClass {}
class DefaultSubclassPrivate : PrivateClass {} // expected-error {{class must be declared private or fileprivate because its superclass is private}}
// expected-note@+1 * {{superclass is declared here}}
public class PublicGenericClass<T> {}
// expected-note@+2 * {{type declared here}}
// expected-note@+1 * {{superclass is declared here}}
internal class InternalGenericClass<T> {}
// expected-note@+1 * {{type declared here}}
private class PrivateGenericClass<T> {}
open class OpenConcreteSubclassInternal : InternalGenericClass<Int> {} // expected-error {{class cannot be declared open because its superclass is internal}} expected-error {{superclass 'InternalGenericClass<Int>' of open class must be open}}
public class PublicConcreteSubclassPublic : PublicGenericClass<Int> {}
public class PublicConcreteSubclassInternal : InternalGenericClass<Int> {} // expected-error {{class cannot be declared public because its superclass is internal}}
public class PublicConcreteSubclassPrivate : PrivateGenericClass<Int> {} // expected-error {{class cannot be declared public because its superclass is private}}
public class PublicConcreteSubclassPublicPrivateArg : PublicGenericClass<PrivateStruct> {} // expected-error {{class cannot be declared public because its superclass uses a private type as a generic parameter}}
public class PublicConcreteSubclassPublicInternalArg : PublicGenericClass<InternalStruct> {} // expected-error {{class cannot be declared public because its superclass uses an internal type as a generic parameter}}
open class OpenConcreteSubclassPublicFilePrivateArg : PublicGenericClass<FilePrivateStruct> {} // expected-error {{class cannot be declared open because its superclass uses a fileprivate type as a generic parameter}} expected-error {{superclass 'PublicGenericClass<FilePrivateStruct>' of open class must be open}}
internal class InternalConcreteSubclassPublicFilePrivateArg : InternalGenericClass<PrivateStruct> {} // expected-error {{class cannot be declared internal because its superclass uses a private type as a generic parameter}}
open class OpenGenericSubclassInternal<T> : InternalGenericClass<T> {} // expected-error {{class cannot be declared open because its superclass is internal}} expected-error {{superclass 'InternalGenericClass<T>' of open class must be open}}
public class PublicGenericSubclassPublic<T> : PublicGenericClass<T> {}
public class PublicGenericSubclassInternal<T> : InternalGenericClass<T> {} // expected-error {{class cannot be declared public because its superclass is internal}}
public class PublicGenericSubclassPrivate<T> : PrivateGenericClass<T> {} // expected-error {{class cannot be declared public because its superclass is private}}
public enum PublicEnumPrivate {
case A(PrivateStruct) // expected-error {{enum case in a public enum uses a private type}}
}
enum DefaultEnumPrivate {
case A(PrivateStruct) // expected-error {{enum case in an internal enum uses a private type}}
}
public enum PublicEnumPI {
case A(InternalStruct) // expected-error {{enum case in a public enum uses an internal type}}
case B(PrivateStruct, InternalStruct) // expected-error {{enum case in a public enum uses a private type}} expected-error {{enum case in a public enum uses an internal type}}
case C(InternalStruct, PrivateStruct) // expected-error {{enum case in a public enum uses an internal type}} expected-error {{enum case in a public enum uses a private type}}
}
enum DefaultEnumPublic {
case A(PublicStruct) // no-warning
}
struct DefaultGeneric<T> {}
struct DefaultGenericPrivate<T: PrivateProto> {} // expected-error {{generic struct must be declared private or fileprivate because its generic parameter uses a private type}}
struct DefaultGenericPrivate2<T: PrivateClass> {} // expected-error {{generic struct must be declared private or fileprivate because its generic parameter uses a private type}}
struct DefaultGenericPrivateReq<T> where T == PrivateClass {} // expected-error {{same-type requirement makes generic parameter 'T' non-generic}}
// expected-error@-1 {{generic struct must be declared private or fileprivate because its generic requirement uses a private type}}
struct DefaultGenericPrivateReq2<T> where T: PrivateProto {} // expected-error {{generic struct must be declared private or fileprivate because its generic requirement uses a private type}}
public struct PublicGenericInternal<T: InternalProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses an internal type}}
public struct PublicGenericPI<T: PrivateProto, U: InternalProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}}
public struct PublicGenericIP<T: InternalProto, U: PrivateProto> {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}}
public struct PublicGenericPIReq<T: PrivateProto> where T: InternalProto {} // expected-error {{generic struct cannot be declared public because its generic parameter uses a private type}}
public struct PublicGenericIPReq<T: InternalProto> where T: PrivateProto {} // expected-error {{generic struct cannot be declared public because its generic requirement uses a private type}}
public func genericFunc<T: InternalProto>(_: T) {} // expected-error {{function cannot be declared public because its generic parameter uses an internal type}} {}
public class GenericClass<T: InternalProto> { // expected-error {{generic class cannot be declared public because its generic parameter uses an internal type}}
public init<T: PrivateProto>(_: T) {} // expected-error {{initializer cannot be declared public because its generic parameter uses a private type}}
public func genericMethod<T: PrivateProto>(_: T) {} // expected-error {{instance method cannot be declared public because its generic parameter uses a private type}}
}
public enum GenericEnum<T: InternalProto> { // expected-error {{generic enum cannot be declared public because its generic parameter uses an internal type}}
case A
}
public protocol PublicMutationOperations {
var size: Int { get set }
subscript (_: Int) -> Int { get set }
}
internal protocol InternalMutationOperations {
var size: Int { get set }
subscript (_: Int) -> Int { get set }
}
public struct AccessorsControl : InternalMutationOperations {
private var size = 0 // expected-error {{property 'size' must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the property as 'internal' to satisfy the requirement}} {{3-10=internal}}
private subscript (_: Int) -> Int { // expected-error {{subscript must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the subscript as 'internal' to satisfy the requirement}} {{3-10=internal}}
get { return 42 }
set {}
}
}
public struct PrivateSettersPublic : InternalMutationOperations {
// Please don't change the formatting here; it's a precise fix-it test.
public private(set) var size = 0 // expected-error {{setter for property 'size' must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the property as 'internal' to satisfy the requirement}} {{10-17=internal}}
public private(set) subscript (_: Int) -> Int { // expected-error {{subscript setter must be declared internal because it matches a requirement in internal protocol 'InternalMutationOperations'}} {{none}} expected-note {{mark the subscript as 'internal' to satisfy the requirement}} {{10-17=internal}}
get { return 42 }
set {}
}
}
internal struct PrivateSettersInternal : PublicMutationOperations {
// Please don't change the formatting here; it's a precise fix-it test.
private(set)var size = 0 // expected-error {{setter for property 'size' must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicMutationOperations'}} {{none}} expected-note {{mark the property as 'internal' to satisfy the requirement}} {{3-15=}}
internal private(set)subscript (_: Int) -> Int { // expected-error {{subscript setter must be as accessible as its enclosing type because it matches a requirement in protocol 'PublicMutationOperations'}} {{none}} expected-note {{mark the subscript as 'internal' to satisfy the requirement}} {{12-24=}}
get { return 42 }
set {}
}
}
public protocol PublicReadOnlyOperations {
var size: Int { get }
subscript (_: Int) -> Int { get }
}
internal struct PrivateSettersForReadOnlyInternal : PublicReadOnlyOperations {
public private(set) var size = 0
internal private(set) subscript (_: Int) -> Int { // no-warning
get { return 42 }
set {}
}
}
public struct PrivateSettersForReadOnlyPublic : PublicReadOnlyOperations {
public private(set) var size = 0 // no-warning
internal private(set) subscript (_: Int) -> Int { // expected-error {{subscript must be declared public because it matches a requirement in public protocol 'PublicReadOnlyOperations'}} {{none}} expected-note {{mark the subscript as 'public' to satisfy the requirement}} {{3-11=public}}
get { return 42 }
set {}
}
}
public protocol PublicOperatorProto {
static prefix func !(_: Self) -> Self
}
internal protocol InternalOperatorProto {
static prefix func !(_: Self) -> Self
}
fileprivate protocol FilePrivateOperatorProto {
static prefix func !(_: Self) -> Self
}
private protocol PrivateOperatorProto {
static prefix func !(_: Self) -> Self
}
public struct PublicOperatorAdopter : PublicOperatorProto {
// expected-error@-1 {{method '!' must be declared public because it matches a requirement in public protocol 'PublicOperatorProto'}}
fileprivate struct Inner : PublicOperatorProto {
}
}
private prefix func !(input: PublicOperatorAdopter) -> PublicOperatorAdopter { // expected-note {{mark the operator function as 'public' to satisfy the requirement}} {{1-8=public}}
return input
}
private prefix func !(input: PublicOperatorAdopter.Inner) -> PublicOperatorAdopter.Inner {
return input
}
public struct InternalOperatorAdopter : InternalOperatorProto {
// expected-error@-1 {{method '!' must be declared internal because it matches a requirement in internal protocol 'InternalOperatorProto'}}
fileprivate struct Inner : InternalOperatorProto {
}
}
private prefix func !(input: InternalOperatorAdopter) -> InternalOperatorAdopter { // expected-note {{mark the operator function as 'internal' to satisfy the requirement}} {{1-8=internal}}
return input
}
private prefix func !(input: InternalOperatorAdopter.Inner) -> InternalOperatorAdopter.Inner {
return input
}
public struct FilePrivateOperatorAdopter : FilePrivateOperatorProto {
fileprivate struct Inner : FilePrivateOperatorProto {
}
}
private prefix func !(input: FilePrivateOperatorAdopter) -> FilePrivateOperatorAdopter {
return input
}
private prefix func !(input: FilePrivateOperatorAdopter.Inner) -> FilePrivateOperatorAdopter.Inner {
return input
}
public struct PrivateOperatorAdopter : PrivateOperatorProto {
fileprivate struct Inner : PrivateOperatorProto {
}
}
private prefix func !(input: PrivateOperatorAdopter) -> PrivateOperatorAdopter {
return input
}
private prefix func !(input: PrivateOperatorAdopter.Inner) -> PrivateOperatorAdopter.Inner {
return input
}
public protocol Equatablish {
static func ==(lhs: Self, rhs: Self) /* -> bool */ // expected-note {{protocol requires function '=='}}
}
fileprivate struct EquatablishOuter {
internal struct Inner : Equatablish {}
}
private func ==(lhs: EquatablishOuter.Inner, rhs: EquatablishOuter.Inner) {}
fileprivate struct EquatablishOuter2 {
internal struct Inner : Equatablish {
fileprivate static func ==(lhs: Inner, rhs: Inner) {}
}
}
fileprivate struct EquatablishOuterProblem {
internal struct Inner : Equatablish { // expected-error {{type 'EquatablishOuterProblem.Inner' does not conform to protocol 'Equatablish'}}
private static func ==(lhs: Inner, rhs: Inner) {}
}
}
internal struct EquatablishOuterProblem2 {
public struct Inner : Equatablish {
fileprivate static func ==(lhs: Inner, rhs: Inner) {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}}
// expected-note@-1 {{mark the operator function as 'internal' to satisfy the requirement}} {{5-16=internal}}
}
}
internal struct EquatablishOuterProblem3 {
public struct Inner : Equatablish { // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}}
}
}
private func ==(lhs: EquatablishOuterProblem3.Inner, rhs: EquatablishOuterProblem3.Inner) {}
// expected-note@-1 {{mark the operator function as 'internal' to satisfy the requirement}} {{1-8=internal}}
internal struct EquatablishOuterProblem4 {
public struct Inner : Equatablish {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}}
}
internal extension EquatablishOuterProblem4.Inner {
fileprivate static func ==(lhs: EquatablishOuterProblem4.Inner, rhs: EquatablishOuterProblem4.Inner) {}
// expected-note@-1 {{mark the operator function as 'internal' to satisfy the requirement}} {{3-15=}}
}
internal struct EquatablishOuterProblem5 {
public struct Inner : Equatablish {} // expected-error {{method '==' must be as accessible as its enclosing type because it matches a requirement in protocol 'Equatablish'}} {{none}}
}
private extension EquatablishOuterProblem5.Inner {
static func ==(lhs: EquatablishOuterProblem5.Inner, rhs: EquatablishOuterProblem5.Inner) {}
// expected-note@-1 {{move the operator function to another extension where it can be declared 'internal' to satisfy the requirement}} {{none}}
}
public protocol AssocTypeProto {
associatedtype Assoc
}
fileprivate struct AssocTypeOuter {
internal struct Inner : AssocTypeProto {
fileprivate typealias Assoc = Int
}
}
fileprivate struct AssocTypeOuterProblem {
internal struct Inner : AssocTypeProto {
private typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}} expected-note {{mark the type alias as 'fileprivate' to satisfy the requirement}} {{5-12=fileprivate}}
}
}
internal struct AssocTypeOuterProblem2 {
public struct Inner : AssocTypeProto {
fileprivate typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}} expected-note {{mark the type alias as 'internal' to satisfy the requirement}} {{5-16=internal}}
}
}
internal struct AssocTypeOuterProblem3 {
public struct Inner : AssocTypeProto {} // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}}
}
internal extension AssocTypeOuterProblem3.Inner {
fileprivate typealias Assoc = Int // expected-note {{mark the type alias as 'internal' to satisfy the requirement}} {{3-15=}}
}
internal struct AssocTypeOuterProblem4 {
public struct Inner : AssocTypeProto {} // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'AssocTypeProto'}} {{none}}
}
private extension AssocTypeOuterProblem4.Inner {
typealias Assoc = Int // expected-note {{move the type alias to another extension where it can be declared 'internal' to satisfy the requirement}} {{none}}
}
internal typealias InternalComposition = PublicClass & PublicProto // expected-note {{declared here}}
public class DerivedFromInternalComposition : InternalComposition { // expected-error {{class cannot be declared public because its superclass is internal}}
public func publicReq() {}
}
internal typealias InternalGenericComposition<T> = PublicGenericClass<T> & PublicProto // expected-note {{declared here}}
public class DerivedFromInternalGenericComposition : InternalGenericComposition<Int> { // expected-error {{class cannot be declared public because its superclass is internal}}
public func publicReq() {}
}
internal typealias InternalConcreteGenericComposition = PublicGenericClass<Int> & PublicProto // expected-note {{declared here}}
public class DerivedFromInternalConcreteGenericComposition : InternalConcreteGenericComposition { // expected-error {{class cannot be declared public because its superclass is internal}}
public func publicReq() {}
}
public typealias BadPublicComposition1 = InternalClass & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias BadPublicComposition2 = PublicClass & InternalProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias BadPublicComposition3<T> = InternalGenericClass<T> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias BadPublicComposition4 = InternalGenericClass<Int> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
public typealias BadPublicComposition5 = PublicGenericClass<InternalStruct> & PublicProto // expected-error {{type alias cannot be declared public because its underlying type uses an internal type}}
open class ClassWithProperties {
open open(set) var openProp = 0 // expected-warning {{'open(set)' modifier is redundant for an open property}} {{8-18=}}
public public(set) var publicProp = 0 // expected-warning {{'public(set)' modifier is redundant for a public property}} {{10-22=}}
internal internal(set) var internalProp = 0 // expected-warning {{'internal(set)' modifier is redundant for an internal property}} {{12-26=}}
fileprivate fileprivate(set) var fileprivateProp = 0 // expected-warning {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{15-32=}}
private private(set) var privateProp = 0 // expected-warning {{'private(set)' modifier is redundant for a private property}} {{11-24=}}
internal(set) var defaultProp = 0 // expected-warning {{'internal(set)' modifier is redundant for an internal property}} {{3-17=}}
}
extension ClassWithProperties {
// expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{12-26=}}
internal internal(set) var defaultExtProp: Int {
get { return 42 }
set {}
}
// expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{3-17=}}
internal(set) var defaultExtProp2: Int {
get { return 42 }
set {}
}
}
public extension ClassWithProperties {
// expected-warning@+2 {{'public' modifier is redundant for property declared in a public extension}} {{3-10=}}
// expected-warning@+1 {{'public(set)' modifier is redundant for a public property}} {{10-22=}}
public public(set) var publicExtProp: Int {
get { return 42 }
set {}
}
// expected-warning@+1 {{'public(set)' modifier is redundant for a public property}} {{3-15=}}
public(set) var publicExtProp2: Int {
get { return 42 }
set {}
}
}
internal extension ClassWithProperties {
// expected-warning@+2 {{'internal' modifier is redundant for property declared in an internal extension}} {{3-12=}}
// expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{12-26=}}
internal internal(set) var internalExtProp: Int {
get { return 42 }
set {}
}
// expected-warning@+1 {{'internal(set)' modifier is redundant for an internal property}} {{3-17=}}
internal(set) var internalExtProp2: Int {
get { return 42 }
set {}
}
}
fileprivate extension ClassWithProperties {
// expected-warning@+2 {{'fileprivate' modifier is redundant for property declared in a fileprivate extension}} {{3-15=}}
// expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{15-32=}}
fileprivate fileprivate(set) var fileprivateExtProp: Int {
get { return 42 }
set {}
}
// expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{3-20=}}
fileprivate(set) var fileprivateExtProp2: Int {
get { return 42 }
set {}
}
private(set) var fileprivateExtProp3: Int {
get { return 42 }
set {}
}
}
private extension ClassWithProperties {
// expected-warning@+2 {{'fileprivate' modifier is redundant for property declared in a private (equivalent to fileprivate) extension}} {{3-15=}}
// expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{15-32=}}
fileprivate fileprivate(set) var privateExtProp: Int {
get { return 42 }
set {}
}
// expected-warning@+1 {{'fileprivate(set)' modifier is redundant for a fileprivate property}} {{3-20=}}
fileprivate(set) var privateExtProp2: Int {
get { return 42 }
set {}
}
private(set) var privateExtProp3: Int {
get { return 42 }
set {}
}
}
public var inferredType = PrivateStruct() // expected-error {{variable cannot be declared public because its type 'PrivateStruct' uses a private type}}
public var inferredGenericParameters: Optional = PrivateStruct() // expected-error {{variable cannot be declared public because its type uses a private type}}
public var explicitType: Optional<PrivateStruct> = PrivateStruct() // expected-error {{variable cannot be declared public because its type uses a private type}}
// rdar://problem/47557376
@objc open class ObjCBase {
init() {}
@objc open dynamic func foo() {}
@objc open dynamic var bar: Int = 0
}
open class ObjCSub: ObjCBase {}
public extension ObjCSub {
// Don't try to remove the 'open', since it's needed to be a valid 'override'.
open override func foo() {} // expected-warning {{'open' modifier conflicts with extension's default access of 'public'}} {{none}}
open override var bar: Int { // expected-warning {{'open' modifier conflicts with extension's default access of 'public'}} {{none}}
get { return 0 }
set {}
}
}
public struct TestGenericSubscripts {
// We'd like these to be errors in a future version of Swift, but they weren't
// in Swift 5.0.
public subscript<T: PrivateProto>(_: T) -> Int { return 0 } // expected-warning {{subscript should not be declared public because its generic parameter uses a private type}} {{none}}
public subscript<T>(where _: T) -> Int where T: PrivateProto { return 0 } // expected-warning {{subscript should not be declared public because its generic requirement uses a private type}} {{none}}
}
public typealias TestGenericAlias<T: PrivateProto> = T // expected-warning {{type alias should not be declared public because its generic parameter uses a private type}}
public typealias TestGenericAliasWhereClause<T> = T where T: PrivateProto // expected-warning {{type alias should not be declared public because its generic requirement uses a private type}}
| 2c8b831493d0a347919ab270e460d304 | 60.718502 | 313 | 0.75012 | false | true | false | false |
SocialbitGmbH/SwiftAddressBook | refs/heads/master | Pod/Classes/SwiftAddressBookPerson.swift | apache-2.0 | 1 | //
// SwiftAddressBookPerson.swift
// Pods
//
// Created by Socialbit - Tassilo Karge on 09.03.15.
//
//
import UIKit
import AddressBook
@available(iOS, deprecated: 9.0)
//MARK: Wrapper for ABAddressBookRecord of type ABPerson
open class SwiftAddressBookPerson : SwiftAddressBookRecord {
open class func create() -> SwiftAddressBookPerson {
return SwiftAddressBookPerson(record: ABPersonCreate().takeRetainedValue())
}
open class func createInSource(_ source : SwiftAddressBookSource) -> SwiftAddressBookPerson {
return SwiftAddressBookPerson(record: ABPersonCreateInSource(source.internalRecord).takeRetainedValue())
}
open class func createInSourceWithVCard(_ source : SwiftAddressBookSource, vCard : String) -> [SwiftAddressBookPerson]? {
guard let data = vCard.data(using: .utf8, allowLossyConversion: true) else {
return nil
}
let persons = ABPersonCreatePeopleInSourceWithVCardRepresentation(source.internalRecord, (data as CFData)).takeRetainedValue() as [ABRecord]
var swiftPersons = [SwiftAddressBookPerson]()
for person in persons {
let swiftPerson = SwiftAddressBookPerson(record: person)
swiftPersons.append(swiftPerson)
}
if swiftPersons.count != 0 {
return swiftPersons
}
else {
return nil
}
}
open class func createVCard(_ people : [SwiftAddressBookPerson]) -> String {
let peopleArray = people.flatMap { $0.internalRecord }
let data = ABPersonCreateVCardRepresentationWithPeople(peopleArray as CFArray).takeRetainedValue() as Data
return String(data: data, encoding: .utf8)!
}
open class func ordering() -> SwiftAddressBookOrdering {
return SwiftAddressBookOrdering(ordering: ABPersonGetSortOrdering())
}
open class func comparePeopleByName(_ person1 : SwiftAddressBookPerson, person2 : SwiftAddressBookPerson, ordering : SwiftAddressBookOrdering) -> CFComparisonResult {
return ABPersonComparePeopleByName(person1.internalRecord, person2.internalRecord, ordering.abPersonSortOrderingValue)
}
//MARK: Personal Information
open func setImage(_ image : UIImage?) -> CFError? {
guard let image = image else { return removeImage() }
let imageData : Data = UIImagePNGRepresentation(image) ?? Data()
return errorIfNoSuccess { ABPersonSetImageData(self.internalRecord, CFDataCreate(nil, (imageData as NSData).bytes.bindMemory(to: UInt8.self, capacity: imageData.count), imageData.count), $0) }
}
open var image : UIImage? {
guard ABPersonHasImageData(internalRecord) else { return nil }
guard let data = ABPersonCopyImageData(internalRecord)?.takeRetainedValue() else { return nil }
return UIImage(data: data as Data)
}
open func imageDataWithFormat(_ format : SwiftAddressBookPersonImageFormat) -> UIImage? {
guard let data = ABPersonCopyImageDataWithFormat(internalRecord, format.abPersonImageFormat)?.takeRetainedValue() else {
return nil
}
return UIImage(data: data as Data)
}
open func hasImageData() -> Bool {
return ABPersonHasImageData(internalRecord)
}
open func removeImage() -> CFError? {
return errorIfNoSuccess { ABPersonRemoveImageData(self.internalRecord, $0) }
}
open var allLinkedPeople : Array<SwiftAddressBookPerson>? {
return convertRecordsToPersons(ABPersonCopyArrayOfAllLinkedPeople(internalRecord).takeRetainedValue())
}
open var source : SwiftAddressBookSource {
return SwiftAddressBookSource(record: ABPersonCopySource(internalRecord).takeRetainedValue())
}
open var compositeNameDelimiterForRecord : String {
return ABPersonCopyCompositeNameDelimiterForRecord(internalRecord).takeRetainedValue() as String
}
open var compositeNameFormat : SwiftAddressBookCompositeNameFormat {
return SwiftAddressBookCompositeNameFormat(format: ABPersonGetCompositeNameFormatForRecord(internalRecord))
}
open var compositeName : String? {
return ABRecordCopyCompositeName(internalRecord)?.takeRetainedValue() as String?
}
open var firstName : String? {
get {
return extractProperty(kABPersonFirstNameProperty)
}
set {
setSingleValueProperty(kABPersonFirstNameProperty, newValue as NSString?)
}
}
open var lastName : String? {
get {
return extractProperty(kABPersonLastNameProperty)
}
set {
setSingleValueProperty(kABPersonLastNameProperty, newValue as NSString?)
}
}
open var middleName : String? {
get {
return extractProperty(kABPersonMiddleNameProperty)
}
set {
setSingleValueProperty(kABPersonMiddleNameProperty, newValue as NSString?)
}
}
open var prefix : String? {
get {
return extractProperty(kABPersonPrefixProperty)
}
set {
setSingleValueProperty(kABPersonPrefixProperty, newValue as NSString?)
}
}
open var suffix : String? {
get {
return extractProperty(kABPersonSuffixProperty)
}
set {
setSingleValueProperty(kABPersonSuffixProperty, newValue as NSString?)
}
}
open var nickname : String? {
get {
return extractProperty(kABPersonNicknameProperty)
}
set {
setSingleValueProperty(kABPersonNicknameProperty, newValue as NSString?)
}
}
open var firstNamePhonetic : String? {
get {
return extractProperty(kABPersonFirstNamePhoneticProperty)
}
set {
setSingleValueProperty(kABPersonFirstNamePhoneticProperty, newValue as NSString?)
}
}
open var lastNamePhonetic : String? {
get {
return extractProperty(kABPersonLastNamePhoneticProperty)
}
set {
setSingleValueProperty(kABPersonLastNamePhoneticProperty, newValue as NSString?)
}
}
open var middleNamePhonetic : String? {
get {
return extractProperty(kABPersonMiddleNamePhoneticProperty)
}
set {
setSingleValueProperty(kABPersonMiddleNamePhoneticProperty, newValue as NSString?)
}
}
open var organization : String? {
get {
return extractProperty(kABPersonOrganizationProperty)
}
set {
setSingleValueProperty(kABPersonOrganizationProperty, newValue as NSString?)
}
}
open var jobTitle : String? {
get {
return extractProperty(kABPersonJobTitleProperty)
}
set {
setSingleValueProperty(kABPersonJobTitleProperty, newValue as NSString?)
}
}
open var department : String? {
get {
return extractProperty(kABPersonDepartmentProperty)
}
set {
setSingleValueProperty(kABPersonDepartmentProperty, newValue as NSString?)
}
}
open var emails : Array<MultivalueEntry<String>>? {
get {
return extractMultivalueProperty(kABPersonEmailProperty)
}
set {
setMultivalueProperty(kABPersonEmailProperty, convertMultivalueEntries(newValue, converter: { $0 as NSString }))
}
}
open var birthday : Date? {
get {
return extractProperty(kABPersonBirthdayProperty)
}
set {
setSingleValueProperty(kABPersonBirthdayProperty, newValue.map { $0 as CFDate})
}
}
open var note : String? {
get {
return extractProperty(kABPersonNoteProperty)
}
set {
setSingleValueProperty(kABPersonNoteProperty, newValue as NSString?)
}
}
open var creationDate : Date? {
get {
return extractProperty(kABPersonCreationDateProperty)
}
set {
setSingleValueProperty(kABPersonCreationDateProperty, newValue.map { $0 as CFDate})
}
}
open var modificationDate : Date? {
get {
return extractProperty(kABPersonModificationDateProperty)
}
set {
setSingleValueProperty(kABPersonModificationDateProperty, newValue.map { $0 as CFDate})
}
}
open var addresses : Array<MultivalueEntry<Dictionary<SwiftAddressBookAddressProperty,Any>>>? {
get {
let keyConverter = {(s : NSString) -> SwiftAddressBookAddressProperty in SwiftAddressBookAddressProperty(property: s as String)}
let valueConverter = { (s : AnyObject) -> AnyObject in return s }
return extractMultivalueDictionaryProperty(kABPersonAddressProperty, keyConverter: keyConverter, valueConverter: valueConverter)
}
set {
setMultivalueDictionaryProperty(kABPersonAddressProperty, newValue, keyConverter: { $0.abAddressProperty as NSString }, valueConverter: { $0 } )
}
}
open var dates : Array<MultivalueEntry<Date>>? {
get {
return extractMultivalueProperty(kABPersonDateProperty)
}
set {
guard let someValue = newValue else {
return
}
let mappedValues = someValue.map { MultivalueEntry(value: ($0.value as CFDate), label: $0.label, id: $0.id) }
setMultivalueProperty(kABPersonDateProperty, mappedValues)
}
}
open var type : SwiftAddressBookPersonType {
get {
return SwiftAddressBookPersonType(type : extractProperty(kABPersonKindProperty))
}
set {
setSingleValueProperty(kABPersonKindProperty, newValue.abPersonType)
}
}
open var phoneNumbers : Array<MultivalueEntry<String>>? {
get {
return extractMultivalueProperty(kABPersonPhoneProperty)
}
set {
setMultivalueProperty(kABPersonPhoneProperty, convertMultivalueEntries(newValue, converter: { $0 as NSString}))
}
}
open var instantMessage : Array<MultivalueEntry<Dictionary<SwiftAddressBookInstantMessagingProperty,String>>>? {
get {
let keyConverter = {(s : NSString) -> SwiftAddressBookInstantMessagingProperty in SwiftAddressBookInstantMessagingProperty(property: s as String)}
let valueConverter = { (s : String) -> String in return s }
return extractMultivalueDictionaryProperty(kABPersonInstantMessageProperty, keyConverter: keyConverter, valueConverter: valueConverter)
}
set {
setMultivalueDictionaryProperty(kABPersonInstantMessageProperty, newValue, keyConverter: { $0.abInstantMessageProperty as NSString }, valueConverter: { $0 as NSString })
}
}
open var socialProfiles : Array<MultivalueEntry<Dictionary<SwiftAddressBookSocialProfileProperty,String>>>? {
get {
let keyConverter = {(s : NSString) -> SwiftAddressBookSocialProfileProperty in SwiftAddressBookSocialProfileProperty(property: s as String)}
let valueConverter = { (s : String) -> String in return s }
return extractMultivalueDictionaryProperty(kABPersonSocialProfileProperty, keyConverter: keyConverter, valueConverter: valueConverter)
}
set {
setMultivalueDictionaryProperty(kABPersonSocialProfileProperty, newValue, keyConverter: { $0.abSocialProfileProperty as NSString }, valueConverter: { $0 as NSString } )
}
}
open var urls : Array<MultivalueEntry<String>>? {
get {
return extractMultivalueProperty(kABPersonURLProperty)
}
set {
setMultivalueProperty(kABPersonURLProperty, convertMultivalueEntries(newValue, converter: { $0 as NSString }))
}
}
open var relatedNames : Array<MultivalueEntry<String>>? {
get {
return extractMultivalueProperty(kABPersonRelatedNamesProperty)
}
set {
setMultivalueProperty(kABPersonRelatedNamesProperty, convertMultivalueEntries(newValue, converter: { $0 as NSString }))
}
}
open var alternateBirthday : Dictionary<String, AnyObject>? {
get {
return extractProperty(kABPersonAlternateBirthdayProperty)
}
set {
let dict : NSDictionary? = newValue as NSDictionary?
setSingleValueProperty(kABPersonAlternateBirthdayProperty, dict)
}
}
//MARK: generic methods to set and get person properties
fileprivate func extractProperty<T>(_ propertyName : ABPropertyID) -> T? {
//the following is two-lines of code for a reason. Do not combine (compiler optimization problems)
let value: AnyObject? = ABRecordCopyValue(self.internalRecord, propertyName)?.takeRetainedValue()
return value as? T
}
fileprivate func setSingleValueProperty<T : AnyObject>(_ key : ABPropertyID,_ value : T?) {
ABRecordSetValue(self.internalRecord, key, value, nil)
}
fileprivate func extractMultivalueProperty<T>(_ propertyName : ABPropertyID) -> Array<MultivalueEntry<T>>? {
guard let multivalue: ABMultiValue = extractProperty(propertyName) else { return nil }
var array = Array<MultivalueEntry<T>>()
for i : Int in 0..<(ABMultiValueGetCount(multivalue)) {
let value : T? = ABMultiValueCopyValueAtIndex(multivalue, i).takeRetainedValue() as? T
if let v : T = value {
let id : Int = Int(ABMultiValueGetIdentifierAtIndex(multivalue, i))
let optionalLabel = ABMultiValueCopyLabelAtIndex(multivalue, i)?.takeRetainedValue()
let optionalLocalziedLabel = optionalLabel == nil ? nil : ABAddressBookCopyLocalizedLabel(optionalLabel)?.takeRetainedValue()
array.append(MultivalueEntry(value: v,
label: optionalLabel == nil ? nil : optionalLabel! as String,
localizedLabel: optionalLocalziedLabel == nil ? nil : optionalLocalziedLabel! as String,
id: id))
}
}
return !array.isEmpty ? array : nil
}
fileprivate func extractMultivalueDictionaryProperty<T : NSCopying, U, V, W>(_ propertyName : ABPropertyID, keyConverter : (T) -> V, valueConverter : (U) -> W ) -> Array<MultivalueEntry<Dictionary<V, W>>>? {
let property : Array<MultivalueEntry<NSDictionary>>? = extractMultivalueProperty(propertyName)
if let array = property {
var array2 : Array<MultivalueEntry<Dictionary<V, W>>> = []
for oldValue in array {
let mv = MultivalueEntry(value: convertNSDictionary(oldValue.value, keyConverter: keyConverter, valueConverter: valueConverter)!, label: oldValue.label, localizedLabel: oldValue.localizedLabel, id: oldValue.id)
array2.append(mv);
}
return array2
}
else {
return nil
}
}
fileprivate func convertNSDictionary<T : NSCopying, U, V, W>(_ d : NSDictionary?, keyConverter : (T) -> V, valueConverter : (U) -> W ) -> Dictionary<V, W>? {
if let d2 = d {
var dict = Dictionary<V,W>()
for key in d2.allKeys as! Array<T> {
let newKey = keyConverter(key)
let newValue = valueConverter(d2[key] as! U)
dict[newKey] = newValue
}
return dict
}
else {
return nil
}
}
fileprivate func convertMultivalueEntries<T,U: AnyObject>(_ multivalue : [MultivalueEntry<T>]?, converter : (T) -> U) -> [MultivalueEntry<U>]? {
var result: [MultivalueEntry<U>]?
if let multivalue = multivalue {
result = []
for m in multivalue {
let convertedValue = converter(m.value)
let converted = MultivalueEntry(value: convertedValue, label: m.label, localizedLabel: m.localizedLabel, id: m.id)
result?.append(converted)
}
}
return result
}
fileprivate func setMultivalueProperty<T : AnyObject>(_ key : ABPropertyID,_ multivalue : Array<MultivalueEntry<T>>?) {
if(multivalue == nil) {
let emptyMultivalue: ABMutableMultiValue = ABMultiValueCreateMutable(ABPersonGetTypeOfProperty(key)).takeRetainedValue()
//TODO: handle possible error
_ = errorIfNoSuccess { ABRecordSetValue(self.internalRecord, key, emptyMultivalue, $0) }
return
}
var abmv : ABMutableMultiValue? = nil
/* make mutable copy to be able to update multivalue */
if let oldValue : ABMultiValue = extractProperty(key) {
abmv = ABMultiValueCreateMutableCopy(oldValue)?.takeRetainedValue()
}
var abmv2 : ABMutableMultiValue? = abmv
/* initialize abmv for sure */
if abmv2 == nil {
abmv2 = ABMultiValueCreateMutable(ABPersonGetTypeOfProperty(key)).takeRetainedValue()
}
let abMultivalue: ABMutableMultiValue = abmv2!
var identifiers = Array<Int>()
for i : Int in 0..<(ABMultiValueGetCount(abMultivalue)) {
identifiers.append(Int(ABMultiValueGetIdentifierAtIndex(abMultivalue, i)))
}
for m : MultivalueEntry in multivalue! {
if identifiers.contains(m.id) {
let index = ABMultiValueGetIndexForIdentifier(abMultivalue, Int32(m.id))
ABMultiValueReplaceValueAtIndex(abMultivalue, m.value, index)
ABMultiValueReplaceLabelAtIndex(abMultivalue, m.label as CFString!, index)
identifiers.remove(at: identifiers.index(of: m.id)!)
}
else {
ABMultiValueAddValueAndLabel(abMultivalue, m.value, m.label as CFString!, nil)
}
}
for i in identifiers {
ABMultiValueRemoveValueAndLabelAtIndex(abMultivalue, ABMultiValueGetIndexForIdentifier(abMultivalue,Int32(i)))
}
ABRecordSetValue(internalRecord, key, abMultivalue, nil)
}
fileprivate func setMultivalueDictionaryProperty<KeyType, ValueType, TargetKeyType: Hashable, TargetValueType: Any>
(_ key : ABPropertyID, _ multivalue : Array<MultivalueEntry<Dictionary<KeyType,ValueType>>>?,keyConverter : @escaping (KeyType) -> TargetKeyType, valueConverter : @escaping (ValueType) -> TargetValueType) {
let array = convertMultivalueEntries(multivalue, converter: { d -> NSDictionary in
var dict = Dictionary<TargetKeyType,TargetValueType>()
for key in d.keys {
dict[keyConverter(key)] = valueConverter(d[key]!)
}
return (dict as NSDictionary?)!
})
setMultivalueProperty(key, array)
}
}
| 0ed0690b40dd06ebbc60f8efd874cf3e | 32.428571 | 226 | 0.740279 | false | false | false | false |
ChrisAU/Locution | refs/heads/master | Papyrus/Views/GameView.swift | mit | 2 | //
// GameView.swift
// Papyrus
//
// Created by Chris Nevin on 22/02/2016.
// Copyright © 2016 CJNevin. All rights reserved.
//
import UIKit
import PapyrusCore
typealias Square = (x: Int, y: Int, rect: CGRect)
typealias Intersection = (x: Int, y: Int, rect: CGRect, intersection: CGRect)
class GameView: UIView {
var tileViewDelegate: TileViewDelegate!
@IBOutlet weak var blackoutView: UIView!
var blanks: Positions {
return tileViews?.flatMap({ $0.isPlaced && $0.isBlank ? Position(x: $0.x!, y: $0.y!) : nil }) ?? []
}
var placedTiles: LetterPositions {
return tileViews?.flatMap({ $0.isPlaced ? LetterPosition(x: $0.x!, y: $0.y!, letter: $0.tile) : nil }) ?? []
}
var boardDrawable: BoardDrawable? {
didSet {
setNeedsDisplay()
}
}
var scoresDrawable: ScoresDrawable? {
didSet {
setNeedsDisplay()
}
}
var rackedTiles: [RackedTile]? {
didSet {
func tileView(for tile: RackedTile) -> TileView {
let view = TileView(frame: tile.rect, tile: tile.tile, points: tile.points, onBoard: false, delegate: tile.movable ? tileViewDelegate : nil)
view.draggable = tile.movable
return view
}
tileViews = rackedTiles?.map(tileView)
}
}
var tileViews: [TileView]? {
willSet {
tileViews?.forEach { $0.removeFromSuperview() }
}
didSet {
tileViews?.forEach { insertSubview($0, belowSubview: blackoutView) }
}
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.saveGState()
boardDrawable?.draw(renderer: context)
scoresDrawable?.draw(renderer: context)
let blackColor = UIColor.black.cgColor
context.setStrokeColor(blackColor)
context.setLineWidth(0.5)
context.strokePath()
context.restoreGState()
}
private var emptySquares: [Square] {
guard let board = boardDrawable?.board, let boardRect = boardDrawable?.rect else { return [] }
let squareSize = boardRect.width / CGFloat(board.size)
func rect(for position: Position) -> CGRect {
return CGRect(x: boardRect.origin.x + CGFloat(position.x) * squareSize,
y: boardRect.origin.y + CGFloat(position.y) * squareSize,
width: squareSize,
height: squareSize)
}
let placed = placedTiles.map({ $0.position })
return board.emptyPositions.filter({ !placed.contains($0) }).flatMap({ ($0.x, $0.y, rect(for: $0)) })
}
func bestIntersection(forRect rect: CGRect) -> Intersection? {
return emptySquares.flatMap({ (x, y, squareRect) -> Intersection? in
let intersection = squareRect.intersection(rect)
return intersection.widthPlusHeight > 0 ? (x, y, squareRect, intersection) : nil
}).sorted(by: { (lhs, rhs) in
return lhs.intersection.widthPlusHeight < rhs.intersection.widthPlusHeight
}).last
}
}
| f60615ac8407545d2d6fc0c3c1816d29 | 33.361702 | 156 | 0.585449 | false | false | false | false |
steve228uk/SRAdaptiveSpaceItem | refs/heads/master | SRAdaptiveSpaceItem.swift | mit | 1 | //
// SRAdaptiveSpaceItem.swift
// Fetch
//
// Created by Stephen Radford on 21/06/2016.
// Copyright © 2016 Cocoon Development Ltd. All rights reserved.
//
import AppKit
public class SRAdaptiveSpaceItem: NSToolbarItem {
override public var label: String {
get {
return ""
}
set { }
}
override public var paletteLabel: String {
get {
return "Adaptive Space"
}
set { }
}
var adaptiveSpaceItemView: AdaptiveSpaceItemView?
var calculatedMinSize: NSSize {
guard let items = toolbar?.items else { return super.minSize }
guard let index = items.indexOf(self) else { return super.minSize }
guard let thisFrame = view?.superview?.frame else { return super.minSize }
if thisFrame.origin.x > 0 {
var space: CGFloat = 0
if items.count > index + 1 {
let nextItem = items[index + 1]
guard let nextFrame = nextItem.view?.superview?.frame else { return super.minSize }
guard let toolbarFrame = nextItem.view?.superview?.superview?.frame else { return super.minSize }
space = (toolbarFrame.size.width - nextFrame.size.width) / 2 - thisFrame.origin.x - 3
if space < 0 { space = 0 }
}
let size = super.minSize
return NSSize(width: space, height: size.height)
}
return super.minSize
}
var calculatedMaxSize: NSSize {
let size = super.maxSize
return NSSize(width: minSize.width, height: size.height)
}
override init(itemIdentifier: String) {
super.init(itemIdentifier: itemIdentifier)
sharedInit()
}
override public func awakeFromNib() {
super.awakeFromNib()
sharedInit()
}
func sharedInit() {
adaptiveSpaceItemView = AdaptiveSpaceItemView(frame: NSMakeRect(0,0,1,1))
adaptiveSpaceItemView?.adaptiveSpaceItem = self
view = adaptiveSpaceItemView
}
func updateWidth() {
minSize = calculatedMinSize
maxSize = calculatedMaxSize
}
}
class AdaptiveSpaceItemView: NSView {
var adaptiveSpaceItem: SRAdaptiveSpaceItem?
override func acceptsFirstMouse(theEvent: NSEvent?) -> Bool {
return true
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(windowResized), name: NSWindowDidResizeNotification, object: window)
adaptiveSpaceItem?.updateWidth()
}
func windowResized(notification: NSNotification) {
adaptiveSpaceItem?.updateWidth()
}
}
| bae24876c33fb85dd8485d7b1b1a3a3b | 26.642857 | 151 | 0.62643 | false | false | false | false |
ericmarkmartin/Nightscouter2 | refs/heads/master | Common/Models/Calibration.swift | mit | 1 | //
// Calibration.swift
// Nightscouter
//
// Created by Peter Ina on 1/11/16.
// Copyright © 2016 Nothingonline. All rights reserved.
//
import Foundation
/// A record type provided by the Nightscout API, contains information required to calculate raw blood glucose level.
public struct Calibration: CustomStringConvertible, Dateable {
public let slope: Double, intercept: Double, scale: Double, milliseconds: Double
public init() {
slope = 856.59
intercept = 32179
scale = 1.0
milliseconds = AppConfiguration.Constant.knownMilliseconds
}
public init(slope: Double, intercept: Double, scale: Double, milliseconds: Double) {
self.slope = slope
self.intercept = intercept
self.scale = scale
self.milliseconds = milliseconds
}
public var description: String {
return "{ Calibration: { slope: \(slope), intercept: \(intercept), scale: \(scale), date: \(date) } }"
}
} | e6874bb307242e67f1b1014b579e0cb1 | 29.8125 | 117 | 0.659898 | false | false | false | false |
Hout/SwiftDate | refs/heads/master | Tests/SwiftDateTests/TestRegion.swift | mit | 1 | //
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import SwiftDate
import XCTest
class TestRegion: XCTestCase {
func testRegionInit() {
SwiftDate.defaultRegion = Region(calendar: Calendars.gregorian, zone: Zones.gmt, locale: Locales.english)
// UTC Region
XCTAssert( (Region.UTC.timeZone.identifier == Zones.gmt.toTimezone().identifier), "Failed to create UTC region")
XCTAssert( (Region.UTC.calendar.identifier == Calendar.autoupdatingCurrent.identifier), "Failed to inherith the appropriate calendar fromd default region")
XCTAssert( (Region.UTC.locale.identifier == Locale.autoupdatingCurrent.identifier), "Failed to inherith the appropriate locale fromd default region")
// New Region
let region1 = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
XCTAssert( (region1.timeZone.identifier == "Europe/Rome"), "Failed to set region's zone")
XCTAssert( (region1.calendar.identifier == Calendar.Identifier.gregorian), "Failed to set region's calendar")
XCTAssert( (region1.locale.identifier == "it"), "Failed to set region's locale")
// Current Region
let currentRegion = Region.current
XCTAssert( (currentRegion.calendar.identifier == Calendar.current.identifier), "Failed to set current's region calendar")
XCTAssert( (currentRegion.timeZone.identifier == TimeZone.current.identifier), "Failed to set current's region timezone")
XCTAssert( (currentRegion.locale.identifier == Locale.current.identifier), "Failed to set current's region locale")
// Default region in another locale and calendar
let modifiedDefaultRegion = Region.currentIn(locale: Locales.japanese, calendar: Calendars.japanese)
XCTAssert( (modifiedDefaultRegion.locale.identifier == Locale(identifier: "ja").identifier), "Failed to create new region from default with modified locale")
XCTAssert( (modifiedDefaultRegion.calendar.identifier == Calendar(identifier: Calendar.Identifier.japanese).identifier), "Failed to create new region from default with modified calendar")
// Default region in another locale and calendar, no action
let unmodifiedDefaultRegion = Region.currentIn()
XCTAssert( (unmodifiedDefaultRegion == SwiftDate.defaultRegion), "currentIn() with no parameters should return unmodified default region")
// Default region in another locale and calendar, only calendar
let modifiedCalendarDefaultRegion = Region.currentIn(calendar: Calendars.buddhist)
XCTAssert( (modifiedCalendarDefaultRegion.calendar.identifier == Calendar.Identifier.buddhist), "currentIn() with modified calendar only does not work")
XCTAssert( (modifiedCalendarDefaultRegion.locale == SwiftDate.defaultRegion.locale), "currentIn() with modified calendar also modify the locale")
// Default region in another locale and calendar, only locale
let modifiedLocaleDefaultRegion = Region.currentIn(locale: Locales.italian)
XCTAssert( (modifiedLocaleDefaultRegion.locale.identifier == Locale(identifier: "it").identifier), "currentIn() with modified locale only does not work")
XCTAssert( (modifiedLocaleDefaultRegion.calendar.identifier == SwiftDate.defaultRegion.calendar.identifier), "currentIn() with modified locale also modify the calendar")
// Init from DateComponents
var dComps = DateComponents()
dComps.calendar = Calendar(identifier: Calendar.Identifier.coptic)
dComps.timeZone = TimeZone(identifier: "Pacific/Truk")
let regionFromComponents = Region(fromDateComponents: dComps)
XCTAssert( (regionFromComponents.calendar == dComps.calendar!), "Failed to create new region from date components / calendar")
XCTAssert( (regionFromComponents.timeZone == dComps.timeZone!), "Failed to create new region from date components / timezone")
// Compare two regions
let regionA = Region(calendar: Calendars.gregorian, zone: Zones.europeOslo, locale: Locales.english)
let regionB = Region(calendar: Calendars.gregorian, zone: Zones.europeOslo, locale: Locales.english)
let regionC = Region(calendar: Calendars.buddhist, zone: Zones.europeOslo, locale: Locales.english)
let regionD = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.english)
let regionE = Region(calendar: Calendars.buddhist, zone: Zones.europeOslo, locale: Locales.italian)
XCTAssert( (regionA == regionB), "Failed to compare two regions")
XCTAssert( (regionC != regionD && regionD != regionE), "Failed to compare two regions")
// Codable/Decodable for Region
do {
let encodedJSON_A = try JSONEncoder().encode(regionA)
let encodedJSON_B = try JSONEncoder().encode(regionB)
XCTAssert( (encodedJSON_A == encodedJSON_B), "Same data regions does not encode the same")
let decodedJSON_RegionA = try JSONDecoder().decode(Region.self, from: encodedJSON_A)
let decodedJSON_RegionB = try JSONDecoder().decode(Region.self, from: encodedJSON_B)
XCTAssert( (decodedJSON_RegionA == decodedJSON_RegionB), "Same data decoded region are not the same")
let stringJSON_A = String(data: encodedJSON_A, encoding: .utf8)
let compareStringJSON_A = "{\"timezone\":\"Europe\\/Oslo\",\"locale\":\"en\",\"calendar\":\"gregorian\"}"
XCTAssert( (stringJSON_A! == compareStringJSON_A), "JSON differ in encodable")
} catch let err {
XCTFail("Failed to test encodable/decodable on Region: \(err)")
}
// Description
let descriptionRegion_A = regionA.description
let expectedDescRegion_A = "{calendar='gregorian', timezone='Europe/Oslo', locale='en'}"
XCTAssert( (descriptionRegion_A == expectedDescRegion_A), "Region description differ from expected")
// Hash value
let hash_regionA = regionA.hashValue
let hash_regionB = regionB.hashValue
XCTAssert( (hash_regionA == hash_regionB), "Hash value fails")
// Current date in this region
let regionIT = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let nowInIT = regionIT.nowInThisRegion()
XCTAssert( (nowInIT.region == regionIT), "Produced date in Region.nowInThisRegion does not have the same origin Region")
XCTAssertInTimeIntervalRange(value: nowInIT.date.timeIntervalSinceNow, range: 2, "Produced date in Region.nowInThisRegion does not have the current date")
// Init with default region data
let regionWithDefault = Region()
XCTAssert( (regionWithDefault == SwiftDate.defaultRegion), "Failed to create new Region from default region")
// Init with only fixed calendar
let defaultRegion_fixedCal = Region(calendar: Calendars.buddhist)
XCTAssert( (defaultRegion_fixedCal.calendar.identifier == Calendar.Identifier.buddhist), "Failed to new region from default with fixed only calendar / different calendar")
XCTAssert( (defaultRegion_fixedCal.locale.identifier == SwiftDate.defaultRegion.locale.identifier), "Failed to new region from default with fixed only calendar / different locale")
XCTAssert( (defaultRegion_fixedCal.timeZone.identifier == SwiftDate.defaultRegion.timeZone.identifier), "Failed to new region from default with fixed only calendar / different timezone")
}
}
func XCTAssertInTimeIntervalRange(value: Double, range: TimeInterval, _ error: String) {
guard value >= (value - range) && value <= (value + range) else {
XCTFail(error)
return
}
}
| 2d2b32cdba2b1262427349b1d8ac18ae | 57.578125 | 189 | 0.765404 | false | false | false | false |
finngaida/healthpad | refs/heads/master | Pad/Pods/Charts/Charts/Classes/Utils/ChartColorTemplates.swift | apache-2.0 | 3 | //
// ChartColorTemplates.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 CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class ChartColorTemplates: NSObject
{
public class func liberty () -> [NSUIColor]
{
return [
NSUIColor(red: 207/255.0, green: 248/255.0, blue: 246/255.0, alpha: 1.0),
NSUIColor(red: 148/255.0, green: 212/255.0, blue: 212/255.0, alpha: 1.0),
NSUIColor(red: 136/255.0, green: 180/255.0, blue: 187/255.0, alpha: 1.0),
NSUIColor(red: 118/255.0, green: 174/255.0, blue: 175/255.0, alpha: 1.0),
NSUIColor(red: 42/255.0, green: 109/255.0, blue: 130/255.0, alpha: 1.0)
]
}
public class func joyful () -> [NSUIColor]
{
return [
NSUIColor(red: 217/255.0, green: 80/255.0, blue: 138/255.0, alpha: 1.0),
NSUIColor(red: 254/255.0, green: 149/255.0, blue: 7/255.0, alpha: 1.0),
NSUIColor(red: 254/255.0, green: 247/255.0, blue: 120/255.0, alpha: 1.0),
NSUIColor(red: 106/255.0, green: 167/255.0, blue: 134/255.0, alpha: 1.0),
NSUIColor(red: 53/255.0, green: 194/255.0, blue: 209/255.0, alpha: 1.0)
]
}
public class func pastel () -> [NSUIColor]
{
return [
NSUIColor(red: 64/255.0, green: 89/255.0, blue: 128/255.0, alpha: 1.0),
NSUIColor(red: 149/255.0, green: 165/255.0, blue: 124/255.0, alpha: 1.0),
NSUIColor(red: 217/255.0, green: 184/255.0, blue: 162/255.0, alpha: 1.0),
NSUIColor(red: 191/255.0, green: 134/255.0, blue: 134/255.0, alpha: 1.0),
NSUIColor(red: 179/255.0, green: 48/255.0, blue: 80/255.0, alpha: 1.0)
]
}
public class func colorful () -> [NSUIColor]
{
return [
NSUIColor(red: 193/255.0, green: 37/255.0, blue: 82/255.0, alpha: 1.0),
NSUIColor(red: 255/255.0, green: 102/255.0, blue: 0/255.0, alpha: 1.0),
NSUIColor(red: 245/255.0, green: 199/255.0, blue: 0/255.0, alpha: 1.0),
NSUIColor(red: 106/255.0, green: 150/255.0, blue: 31/255.0, alpha: 1.0),
NSUIColor(red: 179/255.0, green: 100/255.0, blue: 53/255.0, alpha: 1.0)
]
}
public class func vordiplom () -> [NSUIColor]
{
return [
NSUIColor(red: 192/255.0, green: 255/255.0, blue: 140/255.0, alpha: 1.0),
NSUIColor(red: 255/255.0, green: 247/255.0, blue: 140/255.0, alpha: 1.0),
NSUIColor(red: 255/255.0, green: 208/255.0, blue: 140/255.0, alpha: 1.0),
NSUIColor(red: 140/255.0, green: 234/255.0, blue: 255/255.0, alpha: 1.0),
NSUIColor(red: 255/255.0, green: 140/255.0, blue: 157/255.0, alpha: 1.0)
]
}
public class func colorFromString(colorString: String) -> NSUIColor
{
let leftParenCharset: NSCharacterSet = NSCharacterSet(charactersInString: "( ")
let commaCharset: NSCharacterSet = NSCharacterSet(charactersInString: ", ")
let colorString = colorString.lowercaseString
if colorString.hasPrefix("#")
{
var argb: [UInt] = [255, 0, 0, 0]
let colorString = colorString.unicodeScalars
var length = colorString.count
var index = colorString.startIndex
let endIndex = colorString.endIndex
if length % 2 == 1
{
index = index.advancedBy(1)
length = length - 1
}
if length == 3 || length == 6 || length == 8
{
var i = length == 8 ? 0 : 1
while index < endIndex
{
var c = colorString[index]
index = index.advancedBy(1)
var val = (c.value >= 0x61 && c.value <= 0x66) ? (c.value - 0x61 + 10) : c.value - 0x30
argb[i] = UInt(val) * 16
if length == 3
{
argb[i] = argb[i] + UInt(val)
}
else
{
c = colorString[index]
index = index.advancedBy(1)
val = (c.value >= 0x61 && c.value <= 0x66) ? (c.value - 0x61 + 10) : c.value - 0x30
argb[i] = argb[i] + UInt(val)
}
i = i + 1
}
}
return NSUIColor(red: CGFloat(argb[1]) / 255.0, green: CGFloat(argb[2]) / 255.0, blue: CGFloat(argb[3]) / 255.0, alpha: CGFloat(argb[0]) / 255.0)
}
else if colorString.hasPrefix("rgba")
{
var a: Float = 1.0
var r: Int32 = 0
var g: Int32 = 0
var b: Int32 = 0
let scanner: NSScanner = NSScanner(string: colorString)
scanner.scanString("rgba", intoString: nil)
scanner.scanCharactersFromSet(leftParenCharset, intoString: nil)
scanner.scanInt(&r)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&g)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&b)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanFloat(&a)
return NSUIColor(
red: CGFloat(r) / 255.0,
green: CGFloat(g) / 255.0,
blue: CGFloat(b) / 255.0,
alpha: CGFloat(a)
)
}
else if colorString.hasPrefix("argb")
{
var a: Float = 1.0
var r: Int32 = 0
var g: Int32 = 0
var b: Int32 = 0
let scanner: NSScanner = NSScanner(string: colorString)
scanner.scanString("argb", intoString: nil)
scanner.scanCharactersFromSet(leftParenCharset, intoString: nil)
scanner.scanFloat(&a)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&r)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&g)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&b)
return NSUIColor(
red: CGFloat(r) / 255.0,
green: CGFloat(g) / 255.0,
blue: CGFloat(b) / 255.0,
alpha: CGFloat(a)
)
}
else if colorString.hasPrefix("rgb")
{
var r: Int32 = 0
var g: Int32 = 0
var b: Int32 = 0
let scanner: NSScanner = NSScanner(string: colorString)
scanner.scanString("rgb", intoString: nil)
scanner.scanCharactersFromSet(leftParenCharset, intoString: nil)
scanner.scanInt(&r)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&g)
scanner.scanCharactersFromSet(commaCharset, intoString: nil)
scanner.scanInt(&b)
return NSUIColor(
red: CGFloat(r) / 255.0,
green: CGFloat(g) / 255.0,
blue: CGFloat(b) / 255.0,
alpha: 1.0
)
}
return NSUIColor.clearColor()
}
} | 18dd83af5c4527684316cadc36df9ea2 | 37.567839 | 157 | 0.513943 | false | false | false | false |
Tomikes/jetstream-ios | refs/heads/develop | JetstreamDemos/JetstreamDemos/Shape.swift | mit | 4 | //
// Shape.swift
// Jetstream
//
// Copyright (c) 2014 Uber Technologies, Inc.
//
// 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 Jetstream
class Shape: ModelObject {
dynamic var x: CGFloat = 100
dynamic var y: CGFloat = 100
dynamic var width: CGFloat = 100
dynamic var height: CGFloat = 100
dynamic var color: UIColor = shapeColors[0]
}
let shapeColors = [
"#1dd2af", "#19b698", "#40d47e", "#2cc36b", "#4aa3df", "#2e8ece",
"#a66bbe", "#9b50ba", "#3d566e", "#354b60", "#f2ca27", "#f4a62a",
"#e98b39", "#ec5e00", "#ea6153", "#d14233", "#8c9899"
].map { UIColor.colorWithHexString($0) }
| ed2f1323365089a1cd60f25ba856a4d0 | 41.2 | 81 | 0.712085 | false | false | false | false |
Joneze/PureLayout | refs/heads/master | PureLayout/Example-iOS/Demos/iOSDemo3ViewController.swift | mit | 5 | //
// iOSDemo3ViewController.swift
// PureLayout Example-iOS
//
// Copyright (c) 2015 Tyler Fox
// https://github.com/smileyborg/PureLayout
//
import UIKit
import PureLayout
@objc(iOSDemo3ViewController)
class iOSDemo3ViewController: UIViewController {
let blueView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .blueColor()
return view
}()
let redView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .redColor()
return view
}()
let yellowView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .yellowColor()
return view
}()
let greenView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .greenColor()
return view
}()
var didSetupConstraints = false
override func loadView() {
view = UIView()
view.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
view.addSubview(blueView)
view.addSubview(redView)
view.addSubview(yellowView)
view.addSubview(greenView)
view.setNeedsUpdateConstraints() // bootstrap Auto Layout
}
override func updateViewConstraints() {
if (!didSetupConstraints) {
let views: NSArray = [redView, blueView, yellowView, greenView]
// Fix all the heights of the views to 40 pt
views.autoSetViewsDimension(.Height, toSize: 40.0)
// Distribute the views horizontally across the screen, aligned to one another's horizontal axis,
// with 10 pt spacing between them and to their superview, and their widths matched equally
views.autoDistributeViewsAlongAxis(.Horizontal, alignedTo: .Horizontal, withFixedSpacing: 10.0, insetSpacing: true, matchedSizes: true)
// Align the red view to the horizontal axis of its superview.
// This will end up affecting all the views, since they are all aligned to one another's horizontal axis.
self.redView.autoAlignAxisToSuperviewAxis(.Horizontal)
didSetupConstraints = true
}
super.updateViewConstraints()
}
}
| 58837ba62b305620240e1e6e9cfabe29 | 32.128571 | 147 | 0.623976 | false | false | false | false |
badparking/badparking-ios | refs/heads/master | BadParking/Classes/Account Screen/AccountTableViewController.swift | apache-2.0 | 1 | //
// AccountTableViewController.swift
// BadParking
//
// Created by Roman Simenok on 10/22/16.
// Copyright © 2016 BadParking. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class AccountTableViewController: UITableViewController, FBSDKLoginButtonDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let loginButton = FBSDKLoginButton()
loginButton.readPermissions = ["public_profile", "email"]
loginButton.delegate = self
loginButton.center = self.view.center
self.view.addSubview(loginButton)
self.clearsSelectionOnViewWillAppear = true
}
@IBAction func closePressed(_ sender: UIBarButtonItem) {
self.presentingViewController!.dismiss(animated: true, completion: nil)
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if ((error) != nil) {
// Process error
print(error);
} else if result.isCancelled {
print("Login cancelled")
} else {
let fbToken = result.token.tokenString ?? ""
print("token \(fbToken)")
print(FBSDKAccessToken.current().tokenString)
APIManager.shared.facebookAuth(fbToken) { error in
if let err = error {
print(err);
}
if (APIManager.shared.user?.phone ?? "").isEmpty {
let alert = UIAlertController (
title: "Увага",
message: "Для того щоб ми могли з вами контактувати введіть будь ласка ваш номер телефону",
preferredStyle: UIAlertControllerStyle.alert
)
alert.addTextField(configurationHandler: { (textField: UITextField!) in
textField.placeholder = "+380xxxxxxxxx"
})
alert.addAction(UIAlertAction(title: "Добре", style: .default, handler: { (alertAction: UIAlertAction) in
var phone = alert.textFields?.first?.text ?? ""
phone = phone.replacingOccurrences(of: " ", with: "")
// Validate number locally
APIManager.shared.completetUser(phone: phone, email: nil, complete: { error in
if let err = error {
print(err)
}
})
return
}))
self.present(alert, animated: true, completion: nil)
}
}
}
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
AuthManager.shared.token = nil
print("Did LogOut")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| a75b711c887e2fbd7938d782128fe0ee | 35.690141 | 136 | 0.59904 | false | false | false | false |
rudkx/swift | refs/heads/main | stdlib/private/StdlibUnicodeUnittest/UnicodeScalarProperties.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Unicode scalar tests are currently only avaible on Darwin, awaiting a sensible
// file API...
#if _runtime(_ObjC)
import Foundation
// Cache of opened files
var cachedFiles: [String: String] = [:]
func readInputFile(_ filename: String) -> String {
let path = CommandLine.arguments[2]
do {
guard let cache = cachedFiles[filename] else {
let contents = try String(contentsOfFile: path + filename, encoding: .utf8)
cachedFiles[filename] = contents
return contents
}
return cache
} catch {
fatalError(error.localizedDescription)
}
}
func parseScalars(_ string: String) -> ClosedRange<UInt32> {
// If we have . appear, it means we have a legitimate range. Otherwise,
// it's a singular scalar.
if string.contains(".") {
let range = string.split(separator: ".")
return UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!
} else {
let scalar = UInt32(string, radix: 16)!
return scalar ... scalar
}
}
//===----------------------------------------------------------------------===//
// Binary Properties
//===----------------------------------------------------------------------===//
// Note: If one ever updates this list, be it adding new properties, removing,
// etc., please update the same list found in:
// 'stdlib/public/core/UnicodeScalarProperties.swift'.
let availableBinaryProperties: Set<String> = [
"Alphabetic",
"ASCII_Hex_Digit",
"Bidi_Control",
"Bidi_Mirrored",
"Cased",
"Case_Ignorable",
"Changes_When_Casefolded",
"Changes_When_Casemapped",
"Changes_When_Lowercased",
"Changes_When_NFKC_Casefolded",
"Changes_When_Titlecased",
"Changes_When_Uppercased",
"Dash",
"Default_Ignorable_Code_Point",
"Deprecated",
"Diacritic",
"Emoji",
"Emoji_Modifier",
"Emoji_Modifier_Base",
"Emoji_Presentation",
"Extender",
"Full_Composition_Exclusion",
"Grapheme_Base",
"Grapheme_Extend",
"Hex_Digit",
"ID_Continue",
"ID_Start",
"Ideographic",
"IDS_Binary_Operator",
"IDS_Trinary_Operator",
"Join_Control",
"Logical_Order_Exception",
"Lowercase",
"Math",
"Noncharacter_Code_Point",
"Other_Alphabetic",
"Other_Default_Ignorable_Code_Point",
"Other_Grapheme_Extend",
"Other_ID_Continue",
"Other_ID_Start",
"Other_Lowercase",
"Other_Math",
"Other_Uppercase",
"Pattern_Syntax",
"Pattern_White_Space",
"Quotation_Mark",
"Radical",
"Sentence_Terminal",
"Soft_Dotted",
"Terminal_Punctuation",
"Unified_Ideograph",
"Uppercase",
"Variation_Selector",
"White_Space",
"XID_Continue",
"XID_Start"
]
func parseBinaryProperties(
_ data: String,
into result: inout [String: Set<Unicode.Scalar>]
) {
for line in data.split(separator: "\n") {
// Skip comments
guard !line.hasPrefix("#") else {
continue
}
let info = line.split(separator: "#")
let components = info[0].split(separator: ";")
// Get the property first because we may not care about it.
let filteredProperty = components[1].filter { !$0.isWhitespace }
guard availableBinaryProperties.contains(filteredProperty) else {
continue
}
let filteredScalars = components[0].filter { !$0.isWhitespace }
let scalars = parseScalars(String(filteredScalars))
for scalar in scalars {
result[filteredProperty, default: []].insert(Unicode.Scalar(scalar)!)
}
}
}
// A dictionary of all currently exposed Unicode Scalar Properties. Keyed by
// the literal property name and values being the set of scalars who all conform
// to said property.
public let binaryProperties: [String: Set<Unicode.Scalar>] = {
var result: [String: Set<Unicode.Scalar>] = [:]
#if canImport(Darwin)
let derivedCoreProps = readInputFile("Apple/DerivedCoreProperties.txt")
#else
let derivedCoreProps = readInputFile("DerivedCoreProperties.txt")
#endif
parseBinaryProperties(derivedCoreProps, into: &result)
let derivedNormalizationProps = readInputFile("DerivedNormalizationProps.txt")
parseBinaryProperties(derivedNormalizationProps, into: &result)
let derivedBinaryProperties = readInputFile("DerivedBinaryProperties.txt")
parseBinaryProperties(derivedBinaryProperties, into: &result)
let propList = readInputFile("PropList.txt")
parseBinaryProperties(propList, into: &result)
let emojiData = readInputFile("emoji-data.txt")
parseBinaryProperties(emojiData, into: &result)
return result
}()
//===----------------------------------------------------------------------===//
// Numeric Properties
//===----------------------------------------------------------------------===//
func parseNumericTypes(
_ data: String,
into result: inout [Unicode.Scalar: Unicode.NumericType]
) {
for line in data.split(separator: "\n") {
// Skip comments
guard !line.hasPrefix("#") else {
continue
}
let info = line.split(separator: "#")
let components = info[0].split(separator: ";")
let filteredProperty = components[1].filter { !$0.isWhitespace }
let numericType: Unicode.NumericType
switch filteredProperty {
case "Numeric":
numericType = .numeric
case "Decimal":
numericType = .decimal
case "Digit":
numericType = .digit
default:
continue
}
let filteredScalars = components[0].filter { !$0.isWhitespace }
let scalars = parseScalars(String(filteredScalars))
for scalar in scalars {
result[Unicode.Scalar(scalar)!] = numericType
}
}
}
func parseNumericValues(
_ data: String,
into result: inout [Unicode.Scalar: Double]
) {
for line in data.split(separator: "\n") {
// Skip comments
guard !line.hasPrefix("#") else {
continue
}
let info = line.split(separator: "#")
let components = info[0].split(separator: ";")
let filteredProperty = components[3].filter { !$0.isWhitespace }
let value: Double
// If we have a division, split the numerator and denominator and perform
// the division ourselves to get the correct double value.
if filteredProperty.contains("/") {
let splitDivision = filteredProperty.split(separator: "/")
let numerator = Double(splitDivision[0])!
let denominator = Double(splitDivision[1])!
value = numerator / denominator
} else {
value = Double(filteredProperty)!
}
let filteredScalars = components[0].filter { !$0.isWhitespace }
let scalars = parseScalars(String(filteredScalars))
for scalar in scalars {
result[Unicode.Scalar(scalar)!] = value
}
}
}
// A dictionary of every scalar who has a numeric type and it's value.
public let numericTypes: [Unicode.Scalar: Unicode.NumericType] = {
var result: [Unicode.Scalar: Unicode.NumericType] = [:]
let derivedNumericType = readInputFile("DerivedNumericType.txt")
parseNumericTypes(derivedNumericType, into: &result)
return result
}()
// A dictionary of scalar to numeric value.
public let numericValues: [Unicode.Scalar: Double] = {
var result: [Unicode.Scalar: Double] = [:]
let derivedNumericValues = readInputFile("DerivedNumericValues.txt")
parseNumericValues(derivedNumericValues, into: &result)
return result
}()
//===----------------------------------------------------------------------===//
// Scalar Mappings
//===----------------------------------------------------------------------===//
func parseMappings(
_ data: String,
into result: inout [Unicode.Scalar: [String: String]]
) {
for line in data.split(separator: "\n") {
let components = line.split(separator: ";", omittingEmptySubsequences: false)
let scalarStr = components[0]
guard let scalar = Unicode.Scalar(UInt32(scalarStr, radix: 16)!) else {
continue
}
if let upper = UInt32(components[12], radix: 16) {
let mapping = String(Unicode.Scalar(upper)!)
result[scalar, default: [:]]["upper"] = mapping
}
if let lower = UInt32(components[13], radix: 16) {
let mapping = String(Unicode.Scalar(lower)!)
result[scalar, default: [:]]["lower"] = mapping
}
if let title = UInt32(components[14], radix: 16) {
let mapping = String(Unicode.Scalar(title)!)
result[scalar, default: [:]]["title"] = mapping
}
}
}
func parseSpecialMappings(
_ data: String,
into result: inout [Unicode.Scalar: [String: String]]
) {
for line in data.split(separator: "\n") {
guard !line.hasPrefix("#") else {
continue
}
let components = line.split(separator: ";", omittingEmptySubsequences: false)
// Conditional mappings have an extra component with the conditional name.
// Ignore those.
guard components.count == 5 else {
continue
}
guard let scalar = Unicode.Scalar(UInt32(components[0], radix: 16)!) else {
continue
}
let lower = components[1].split(separator: " ").map {
Character(Unicode.Scalar(UInt32($0, radix: 16)!)!)
}
let title = components[2].split(separator: " ").map {
Character(Unicode.Scalar(UInt32($0, radix: 16)!)!)
}
let upper = components[3].split(separator: " ").map {
Character(Unicode.Scalar(UInt32($0, radix: 16)!)!)
}
if lower.count != 1 {
result[scalar, default: [:]]["lower"] = String(lower)
}
if title.count != 1 {
result[scalar, default: [:]]["title"] = String(title)
}
if upper.count != 1 {
result[scalar, default: [:]]["upper"] = String(upper)
}
}
}
// A dictionary of every scalar mapping keyed by the scalar and returning another
// dictionary who is then keyed by either "lower", "upper", or "title".
public let mappings: [Unicode.Scalar: [String: String]] = {
var result: [Unicode.Scalar: [String: String]] = [:]
#if canImport(Darwin)
let unicodeData = readInputFile("Apple/UnicodeData.txt")
#else
let unicodeData = readInputFile("UnicodeData.txt")
#endif
let specialCasing = readInputFile("SpecialCasing.txt")
parseMappings(unicodeData, into: &result)
parseSpecialMappings(specialCasing, into: &result)
return result
}()
//===----------------------------------------------------------------------===//
// Scalar Age
//===----------------------------------------------------------------------===//
func parseAge(
_ data: String,
into result: inout [Unicode.Scalar: Unicode.Version]
) {
for line in data.split(separator: "\n") {
// Skip comments
guard !line.hasPrefix("#") else {
continue
}
let info = line.split(separator: "#")
let components = info[0].split(separator: ";")
let filteredScalars = components[0].filter { !$0.isWhitespace }
let scalars = parseScalars(String(filteredScalars))
let version = components[1].filter { !$0.isWhitespace }
let parts = version.split(separator: ".")
let major = Int(parts[0])!
let minor = Int(parts[1])!
for scalar in scalars {
guard let scalar = Unicode.Scalar(scalar) else {
continue
}
result[scalar] = (major, minor)
}
}
}
public let ages: [Unicode.Scalar: Unicode.Version] = {
var result: [Unicode.Scalar: Unicode.Version] = [:]
let derivedAge = readInputFile("DerivedAge.txt")
parseAge(derivedAge, into: &result)
return result
}()
//===----------------------------------------------------------------------===//
// Scalar General Category
//===----------------------------------------------------------------------===//
func parseGeneralCategory(
_ data: String,
into result: inout [Unicode.Scalar: Unicode.GeneralCategory]
) {
for line in data.split(separator: "\n") {
// Skip comments
guard !line.hasPrefix("#") else {
continue
}
let info = line.split(separator: "#")
let components = info[0].split(separator: ";")
let filteredCategory = components[1].filter { !$0.isWhitespace }
let category: Unicode.GeneralCategory
switch filteredCategory {
case "Lu":
category = .uppercaseLetter
case "Ll":
category = .lowercaseLetter
case "Lt":
category = .titlecaseLetter
case "Lm":
category = .modifierLetter
case "Lo":
category = .otherLetter
case "Mn":
category = .nonspacingMark
case "Mc":
category = .spacingMark
case "Me":
category = .enclosingMark
case "Nd":
category = .decimalNumber
case "Nl":
category = .letterNumber
case "No":
category = .otherNumber
case "Pc":
category = .connectorPunctuation
case "Pd":
category = .dashPunctuation
case "Ps":
category = .openPunctuation
case "Pe":
category = .closePunctuation
case "Pi":
category = .initialPunctuation
case "Pf":
category = .finalPunctuation
case "Po":
category = .otherPunctuation
case "Sm":
category = .mathSymbol
case "Sc":
category = .currencySymbol
case "Sk":
category = .modifierSymbol
case "So":
category = .otherSymbol
case "Zs":
category = .spaceSeparator
case "Zl":
category = .lineSeparator
case "Zp":
category = .paragraphSeparator
case "Cc":
category = .control
case "Cf":
category = .format
case "Cs":
category = .surrogate
case "Co":
category = .privateUse
case "Cn":
category = .unassigned
default:
continue
}
let filteredScalars = components[0].filter { !$0.isWhitespace }
let scalars = parseScalars(String(filteredScalars))
for scalar in scalars {
guard let scalar = Unicode.Scalar(scalar) else {
continue
}
result[scalar] = category
}
}
}
public let generalCategories: [Unicode.Scalar: Unicode.GeneralCategory] = {
var result: [Unicode.Scalar: Unicode.GeneralCategory] = [:]
let derivedGeneralCategory = readInputFile("DerivedGeneralCategory.txt")
parseGeneralCategory(derivedGeneralCategory, into: &result)
return result
}()
//===----------------------------------------------------------------------===//
// Scalar Name Alias
//===----------------------------------------------------------------------===//
func parseNameAliases(
_ data: String,
into result: inout [Unicode.Scalar: String]
) {
for line in data.split(separator: "\n") {
// Skip comments
guard !line.hasPrefix("#") else {
continue
}
let info = line.split(separator: "#")
let components = info[0].split(separator: ";")
// Name aliases are only found with correction attribute.
guard components[2] == "correction" else {
continue
}
let filteredScalars = components[0].filter { !$0.isWhitespace }
guard let scalar = Unicode.Scalar(UInt32(filteredScalars, radix: 16)!) else {
continue
}
let nameAlias = String(components[1])
result[scalar] = nameAlias
}
}
public let nameAliases: [Unicode.Scalar: String] = {
var result: [Unicode.Scalar: String] = [:]
let nameAliases = readInputFile("NameAliases.txt")
parseNameAliases(nameAliases, into: &result)
return result
}()
//===----------------------------------------------------------------------===//
// Scalar Name
//===----------------------------------------------------------------------===//
func parseNames(
_ data: String,
into result: inout [Unicode.Scalar: String]
) {
for line in data.split(separator: "\n") {
// Skip comments
guard !line.hasPrefix("#") else {
continue
}
let info = line.split(separator: "#")
let components = info[0].split(separator: ";")
let filteredScalars = components[0].filter { !$0.isWhitespace }
let scalars = parseScalars(String(filteredScalars))
// If our scalar is a range of scalars, then the name is usually something
// like NAME-HERE-* where * is the scalar value.
if scalars.count > 1 {
for scalar in scalars {
guard let scalar = Unicode.Scalar(scalar) else {
continue
}
var name = String(components[1])
// There's leftover spacing in the beginning of the name that we need to
// get rid of.
name.removeFirst()
name.removeLast()
name += "\(String(scalar.value, radix: 16, uppercase: true))"
result[scalar] = name
}
} else {
guard let scalar = Unicode.Scalar(scalars.lowerBound) else {
continue
}
var name = String(components[1])
// There's leftover spacing in the beginning of the name that we need to
// get rid of.
name.removeFirst()
result[scalar] = name
}
}
}
public let names: [Unicode.Scalar: String] = {
var result: [Unicode.Scalar: String] = [:]
let derivedName = readInputFile("DerivedName.txt")
parseNames(derivedName, into: &result)
return result
}()
#endif
| 064f81084c25cbd6687eb871db2b0045 | 26.092476 | 81 | 0.60457 | false | false | false | false |
Ryan-Vanderhoef/Antlers | refs/heads/master | AppIdea/Frameworks/Bond/Bond/Bond+UIButton.swift | mit | 1 | //
// Bond+UIButton.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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 class ButtonDynamicHelper
{
weak var control: UIButton?
var listener: (UIControlEvents -> Void)?
init(control: UIButton) {
self.control = control
control.addTarget(self, action: Selector("touchDown:"), forControlEvents: .TouchDown)
control.addTarget(self, action: Selector("touchUpInside:"), forControlEvents: .TouchUpInside)
control.addTarget(self, action: Selector("touchUpOutside:"), forControlEvents: .TouchUpOutside)
control.addTarget(self, action: Selector("touchCancel:"), forControlEvents: .TouchCancel)
}
func touchDown(control: UIButton) {
self.listener?(.TouchDown)
}
func touchUpInside(control: UIButton) {
self.listener?(.TouchUpInside)
}
func touchUpOutside(control: UIButton) {
self.listener?(.TouchUpOutside)
}
func touchCancel(control: UIButton) {
self.listener?(.TouchCancel)
}
deinit {
control?.removeTarget(self, action: nil, forControlEvents: .AllEvents)
}
}
class ButtonDynamic<T>: Dynamic<UIControlEvents>
{
let helper: ButtonDynamicHelper
init(control: UIButton) {
self.helper = ButtonDynamicHelper(control: control)
super.init(UIControlEvents.allZeros)
self.helper.listener = { [unowned self] in
self.value = $0
}
self.faulty = true
}
}
private var eventDynamicHandleUIButton: UInt8 = 0;
private var enabledDynamicHandleUIButton: UInt8 = 0;
private var titleDynamicHandleUIButton: UInt8 = 0;
private var imageForNormalStateDynamicHandleUIButton: UInt8 = 0;
extension UIButton /*: Dynamical, Bondable */ {
public var dynEvent: Dynamic<UIControlEvents> {
if let d: AnyObject = objc_getAssociatedObject(self, &eventDynamicHandleUIButton) {
return (d as? Dynamic<UIControlEvents>)!
} else {
let d = ButtonDynamic<UIControlEvents>(control: self)
objc_setAssociatedObject(self, &eventDynamicHandleUIButton, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var dynEnabled: Dynamic<Bool> {
if let d: AnyObject = objc_getAssociatedObject(self, &enabledDynamicHandleUIButton) {
return (d as? Dynamic<Bool>)!
} else {
let d = InternalDynamic<Bool>(self.enabled, faulty: false)
let bond = Bond<Bool>() { [weak self] v in if let s = self { s.enabled = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &enabledDynamicHandleUIButton, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var dynTitle: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &titleDynamicHandleUIButton) {
return (d as? Dynamic<String>)!
} else {
let d = InternalDynamic<String>(self.titleLabel?.text ?? "", faulty: false)
let bond = Bond<String>() { [weak self] v in if let s = self { s.setTitle(v, forState: .Normal) } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &titleDynamicHandleUIButton, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var dynImageForNormalState: Dynamic<UIImage?> {
if let d: AnyObject = objc_getAssociatedObject(self, &imageForNormalStateDynamicHandleUIButton) {
return (d as? Dynamic<UIImage?>)!
} else {
let d = InternalDynamic<UIImage?>(self.imageForState(.Normal), faulty: false)
let bond = Bond<UIImage?>() { [weak self] img in if let s = self { s.setImage(img, forState: .Normal) } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &imageForNormalStateDynamicHandleUIButton, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedDynamic: Dynamic<UIControlEvents> {
return self.dynEvent
}
public var designatedBond: Bond<Bool> {
return self.dynEnabled.valueBond
}
}
public func ->> (left: UIButton, right: Bond<UIControlEvents>) {
left.designatedDynamic ->> right
}
public func ->> <U: Bondable where U.BondType == UIControlEvents>(left: UIButton, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> <T: Dynamical where T.DynamicType == Bool>(left: T, right: UIButton) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: Dynamic<Bool>, right: UIButton) {
left ->> right.designatedBond
}
| e1896febd44d5d480d4121314cb9e4e1 | 34.641509 | 141 | 0.708664 | false | false | false | false |
jovito-royeca/Decktracker | refs/heads/master | ios/old/Decktracker/View/Search/SearchFilterViewController.swift | apache-2.0 | 1 | //
// SearchFilterViewController.swift
// Decktracker
//
// Created by Jovit Royeca on 6/9/15.
// Copyright (c) 2015 Jovito Royeca. All rights reserved.
//
import UIKit
class SearchFilterViewController: XLFormViewController {
enum Tags : String {
case SearchInName = "searchInName"
case SearchInText = "searchInText"
case SearchInFlavor = "searchInFlavor"
case SearchBlack = "SearchInBlack"
case SearchBlue = "searchInBlue"
case SearchGreen = "SearchInGreen"
case SearchRed = "SearchInRed"
case SearchWhite = "searchInWhite"
case SearchColorless = "SearchInColorless"
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.initializeForm()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initializeForm()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
var manaImage:UIImage?
var userKey:AnyObject?
form = XLFormDescriptor(title: "Search Filter")
section = XLFormSectionDescriptor.formSectionWithTitle("Search Terms")
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.SearchInName.rawValue, rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "Search In Name")
userKey = NSUserDefaults.standardUserDefaults().objectForKey(Tags.SearchInName.rawValue)
row.value = userKey != nil ? userKey!.boolValue : 1
row.onChangeBlock = { (oldValue: AnyObject?, newValue: AnyObject?, rowDescriptor: XLFormRowDescriptor?) -> Void in
NSUserDefaults.standardUserDefaults().setBool(newValue!.boolValue, forKey: Tags.SearchInName.rawValue)
}
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.SearchInText.rawValue, rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "Search In Text")
userKey = NSUserDefaults.standardUserDefaults().objectForKey(Tags.SearchInText.rawValue)
row.value = userKey != nil ? userKey!.boolValue : 1
row.onChangeBlock = { (oldValue: AnyObject?, newValue: AnyObject?, rowDescriptor: XLFormRowDescriptor?) -> Void in
NSUserDefaults.standardUserDefaults().setBool(newValue!.boolValue, forKey: Tags.SearchInText.rawValue)
}
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.SearchInFlavor.rawValue, rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "Search In Flavor")
userKey = NSUserDefaults.standardUserDefaults().objectForKey(Tags.SearchInFlavor.rawValue)
row.value = userKey != nil ? userKey!.boolValue : 1
row.onChangeBlock = { (oldValue: AnyObject?, newValue: AnyObject?, rowDescriptor: XLFormRowDescriptor?) -> Void in
NSUserDefaults.standardUserDefaults().setBool(newValue!.boolValue, forKey: Tags.SearchInFlavor.rawValue)
}
section.addFormRow(row)
// Search By Mana color
section = XLFormSectionDescriptor.formSectionWithTitle("Search By Color")
form.addFormSection(section)
row = XLFormRowDescriptor(tag: Tags.SearchBlack.rawValue, rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "Black")
userKey = NSUserDefaults.standardUserDefaults().objectForKey(Tags.SearchBlack.rawValue)
row.value = userKey != nil ? userKey!.boolValue : 1
row.onChangeBlock = { (oldValue: AnyObject?, newValue: AnyObject?, rowDescriptor: XLFormRowDescriptor?) -> Void in
NSUserDefaults.standardUserDefaults().setBool(newValue!.boolValue, forKey: Tags.SearchBlack.rawValue)
}
manaImage = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/mana/B/32.png");
row.cellConfig["imageView.image"] = JJJUtil.imageWithImage(manaImage, scaledToSize:CGSize(width: manaImage!.size.width/2, height:manaImage!.size.height/2))
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.SearchBlue.rawValue, rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "Blue")
userKey = NSUserDefaults.standardUserDefaults().objectForKey(Tags.SearchBlue.rawValue)
row.value = userKey != nil ? userKey!.boolValue : 1
row.onChangeBlock = { (oldValue: AnyObject?, newValue: AnyObject?, rowDescriptor: XLFormRowDescriptor?) -> Void in
NSUserDefaults.standardUserDefaults().setBool(newValue!.boolValue, forKey: Tags.SearchBlue.rawValue)
}
manaImage = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/mana/U/32.png");
row.cellConfig["imageView.image"] = JJJUtil.imageWithImage(manaImage, scaledToSize:CGSize(width: manaImage!.size.width/2, height:manaImage!.size.height/2))
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.SearchGreen.rawValue, rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "Green")
userKey = NSUserDefaults.standardUserDefaults().objectForKey(Tags.SearchGreen.rawValue)
row.value = userKey != nil ? userKey!.boolValue : 1
row.onChangeBlock = { (oldValue: AnyObject?, newValue: AnyObject?, rowDescriptor: XLFormRowDescriptor?) -> Void in
NSUserDefaults.standardUserDefaults().setBool(newValue!.boolValue, forKey: Tags.SearchGreen.rawValue)
}
manaImage = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/mana/G/32.png");
row.cellConfig["imageView.image"] = JJJUtil.imageWithImage(manaImage, scaledToSize:CGSize(width: manaImage!.size.width/2, height:manaImage!.size.height/2))
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.SearchRed.rawValue, rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "Red")
userKey = NSUserDefaults.standardUserDefaults().objectForKey(Tags.SearchRed.rawValue)
row.value = userKey != nil ? userKey!.boolValue : 1
row.onChangeBlock = { (oldValue: AnyObject?, newValue: AnyObject?, rowDescriptor: XLFormRowDescriptor?) -> Void in
NSUserDefaults.standardUserDefaults().setBool(newValue!.boolValue, forKey: Tags.SearchRed.rawValue)
}
manaImage = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/mana/R/32.png");
row.cellConfig["imageView.image"] = JJJUtil.imageWithImage(manaImage, scaledToSize:CGSize(width: manaImage!.size.width/2, height:manaImage!.size.height/2))
section.addFormRow(row)
row = XLFormRowDescriptor(tag: Tags.SearchWhite.rawValue, rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "White")
userKey = NSUserDefaults.standardUserDefaults().objectForKey(Tags.SearchWhite.rawValue)
row.value = userKey != nil ? userKey!.boolValue : 1
row.onChangeBlock = { (oldValue: AnyObject?, newValue: AnyObject?, rowDescriptor: XLFormRowDescriptor?) -> Void in
NSUserDefaults.standardUserDefaults().setBool(newValue!.boolValue, forKey: Tags.SearchWhite.rawValue)
}
manaImage = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/mana/W/32.png");
row.cellConfig["imageView.image"] = JJJUtil.imageWithImage(manaImage, scaledToSize:CGSize(width: manaImage!.size.width/2, height:manaImage!.size.height/2))
section.addFormRow(row)
// row = XLFormRowDescriptor(tag: Tags.SearchColorless.rawValue, rowType: XLFormRowDescriptorTypeBooleanSwitch, title: "Colorless")
// userKey = NSUserDefaults.standardUserDefaults().objectForKey(Tags.SearchColorless.rawValue)
// row.value = userKey != nil ? userKey!.boolValue : 1
// row.onChangeBlock = { (oldValue: AnyObject?, newValue: AnyObject?, rowDescriptor: XLFormRowDescriptor?) -> Void in
// NSUserDefaults.standardUserDefaults().setBool(newValue!.boolValue, forKey: Tags.SearchColorless.rawValue)
// }
// manaImage = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/mana/Colorless/32.png");
// row.cellConfig["imageView.image"] = JJJUtil.imageWithImage(manaImage, scaledToSize:CGSize(width: manaImage!.size.width/2, height:manaImage!.size.height/2))
// section.addFormRow(row)
self.form = form
}
}
| f243c9bd5b61913598436861f25244f2 | 60.355072 | 165 | 0.700602 | false | false | false | false |
Jnosh/swift | refs/heads/master | test/Reflection/Inputs/TypeLowering.swift | apache-2.0 | 20 | public struct BasicStruct {
public let i1: Int8
public let i2: Int16
public let i3: Int32
public let bi1: Box<Int8>
public let bi2: Box<Int16>
public let bi3: Box<Int32>
}
public struct Box<T> {
public let value: T
}
public protocol P {
associatedtype A
associatedtype B
}
public protocol Q : P {}
public struct ConformsP<T, U> : P {
public typealias A = Box<U>
public typealias B = Box<T>
}
public struct ConformsQ<T, U> : Q {
public typealias A = Box<U>
public typealias B = Box<T>
}
public class Base<T, U> : P {
public typealias A = Box<T>
public typealias B = Box<U>
}
public class Derived : Base<Int8, Int16> {}
public class GenericDerived<T> : Base<T, T> {}
public struct Bar<T : P> {
public let a: T.A
public let b: T.B
public let c: (T.A, T.B)
}
public struct AssocTypeStruct {
public let t1: Bar<ConformsP<Int8, Int16>>
public let t2: Bar<ConformsQ<Int8, Int16>>
public let t3: Bar<Base<Int8, Int16>>
public let t4: Bar<Derived>
public let t5: Bar<GenericDerived<Int8>>
}
public class C {}
public struct ReferenceStruct {
public let strongRef: C
public let optionalStrongRef: C?
public let strongRefTuple: (C, C)
public let optionalStrongRefTuple: (C, C)?
public unowned let unownedRef: C
public weak var weakRef: C?
public unowned(unsafe) let unmanagedRef: C
}
public struct FunctionStruct {
public let thickFunction: () -> ()
public let optionalThickFunction: (() -> ())?
public let thinFunction: @convention(thin) () -> ()
public let optionalThinFunction: (@convention(thin) () -> ())?
public let cFunction: @convention(c) () -> ()
public let optionalCFunction: (@convention(c) () -> ())?
}
public protocol P1 {}
public protocol P2 : P1 {}
public protocol P3 {}
public protocol CP1 : class {}
public protocol CP2 : CP1 {}
public struct ExistentialStruct {
public let any: Any
public let optionalAny: Any?
public let anyObject: AnyObject
public let optionalAnyObject: AnyObject?
public let anyProto: P1
public let optionalAnyProto: P1?
public let anyProtoComposition: P1 & P2 & P3
public let optionalAnyProtoComposition: (P1 & P2 & P3)?
public let anyClassBoundProto1: CP1
public let optionalAnyClassBoundProto1: CP1?
public let anyClassBoundProto2: CP2
public let optionalAnyClassBoundProto2: CP2?
public let anyClassBoundProtoComposition1: CP1 & CP2
public let optionalAnyClassBoundProtoComposition1: (CP1 & CP2)?
public let anyClassBoundProtoComposition2: P1 & CP2
public let optionalAnyClassBoundProtoComposition2: (P1 & CP2)?
public weak var weakAnyObject: AnyObject?
public weak var weakAnyClassBoundProto: CP1?
public let classConstrainedP1: C & P1
}
public struct MetadataHolder<T, U> {
let t: T
let u: U.Type
}
public struct MetatypeStruct {
public let any: Any.Type
public let optionalAny: Any.Type?
public let anyObject: AnyObject.Type
public let optionalAnyObject: AnyObject.Type?
public let anyProto: P1.Type
public let optionalAnyProto: P1.Type?
public let anyProtoComposition: (P1 & P2 & P3).Type
public let optionalAnyProtoComposition: (P1 & P2 & P3).Type?
public let structMetatype: BasicStruct.Type
public let optionalStructMetatype: BasicStruct.Type?
public let classMetatype: C.Type
public let optionalClassMetatype: C.Type?
public let abstractMetatype: MetadataHolder<BasicStruct.Type, BasicStruct>
}
public enum EmptyEnum {}
public enum NoPayloadEnum {
case A
case B
case C
case D
}
public enum SillyNoPayloadEnum {
case A(EmptyEnum)
case B(EmptyEnum)
case C
case D
}
public enum SingletonEnum {
case Payload(C)
}
public enum SinglePayloadEnum {
indirect case Indirect(Any)
case Nothing
}
public enum MultiPayloadConcrete {
case Left(C)
case Right(C)
case Donkey
case Mule
case Horse
}
public enum MultiPayloadGenericFixed<T : C> {
case Left(T)
case Right(T)
case Donkey
case Mule
case Horse
}
public enum MultiPayloadGenericDynamic<T, U> {
case Left(T)
case Right(U)
case Donkey
case Mule
case Horse
}
public struct EnumStruct {
public let empty: EmptyEnum
public let noPayload: NoPayloadEnum
public let sillyNoPayload: SillyNoPayloadEnum
public let singleton: SingletonEnum
public let singlePayload: SinglePayloadEnum
public let multiPayloadConcrete: MultiPayloadConcrete
public let multiPayloadGenericFixed: MultiPayloadGenericFixed<C>
public let multiPayloadGenericDynamic: MultiPayloadGenericDynamic<Int8, Int>
// Double-optional class reference does not need
// any extra storage
public let optionalOptionalRef: C??
// Double-optional raw pointer needs an extra
// tag byte
public let optionalOptionalPtr: UnsafePointer<Int>??
}
| 4be59e72e2cf5807be71853252ddc607 | 21.163551 | 78 | 0.728442 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | StripePayments/StripePayments/API Bindings/Models/STPConnectAccountParams.swift | mit | 1 | //
// STPConnectAccountParams.swift
// StripePayments
//
// Created by Daniel Jackson on 1/4/18.
// Copyright © 2018 Stripe, Inc. All rights reserved.
//
import Foundation
/// The business type of the Connect account.
@objc public enum STPConnectAccountBusinessType: Int {
/// This Connect account represents an individual.
case individual
/// This Connect account represents a company.
case company
}
/// Parameters for creating a Connect Account token.
/// - seealso: https://stripe.com/docs/api/tokens/create_account
public class STPConnectAccountParams: NSObject {
/// Boolean indicating that the Terms Of Service were shown to the user &
/// the user accepted them.
@objc public let tosShownAndAccepted: NSNumber?
/// The business type.
@objc public let businessType: STPConnectAccountBusinessType
/// Information about the individual represented by the account.
@objc public let individual: STPConnectAccountIndividualParams?
/// Information about the company or business.
@objc public let company: STPConnectAccountCompanyParams?
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
/// Initialize `STPConnectAccountParams` with tosShownAndAccepted = YES
/// This method cannot be called with `wasAccepted == NO`, guarded by a `NSParameterAssert()`.
/// Use this init method if you want to set the `tosShownAndAccepted` parameter. If you
/// don't, use the `initWithIndividual:` version instead.
/// - Parameters:
/// - wasAccepted: Must be YES, but only if the user was shown & accepted the ToS
/// - individual: Information about the person represented by the account. See `STPConnectAccountIndividualParams`.
@objc public init?(
tosShownAndAccepted wasAccepted: Bool,
individual: STPConnectAccountIndividualParams
) {
// It is an error to call this method with wasAccepted == NO
guard wasAccepted == true else {
return nil
}
self.tosShownAndAccepted = wasAccepted as NSNumber
self.individual = individual
self.company = nil
self.businessType = .individual
super.init()
}
/// Initialize `STPConnectAccountParams` with tosShownAndAccepted = YES
/// This method cannot be called with `wasAccepted == NO`, guarded by a `NSParameterAssert()`.
/// Use this init method if you want to set the `tosShownAndAccepted` parameter. If you
/// don't, use the `initWithCompany:` version instead.
/// - Parameters:
/// - wasAccepted: Must be YES, but only if the user was shown & accepted the ToS
/// - company: Information about the company or business. See `STPConnectAccountCompanyParams`.
@objc public init?(
tosShownAndAccepted wasAccepted: Bool,
company: STPConnectAccountCompanyParams
) {
// It is an error to call this method with wasAccepted == NO
guard wasAccepted == true else {
return nil
}
self.tosShownAndAccepted = wasAccepted as NSNumber
self.individual = nil
self.company = company
self.businessType = .company
super.init()
}
/// Initialize `STPConnectAccountParams` with the provided `individual` dictionary.
/// - Parameter individual: Information about the person represented by the account
/// This init method cannot change the `tosShownAndAccepted` parameter. Use
/// `initWithTosShownAndAccepted:individual:` instead if you need to do that.
@objc
public init(
individual: STPConnectAccountIndividualParams
) {
tosShownAndAccepted = false
self.individual = individual
self.company = nil
businessType = .individual
super.init()
}
/// Initialize `STPConnectAccountParams` with the provided `company` dictionary.
/// - Parameter company: Information about the company or business
/// This init method cannot change the `tosShownAndAccepted` parameter. Use
/// `initWithTosShownAndAccepted:company:` instead if you need to do that.
@objc
public init(
company: STPConnectAccountCompanyParams
) {
tosShownAndAccepted = false
self.individual = nil
self.company = company
businessType = .company
super.init()
}
// MARK: - description
/// :nodoc:
@objc public override var description: String {
let props: [String] = [
String(format: "%@: %p", NSStringFromClass(STPConnectAccountParams.self), self),
// We use NSParameterAssert to block this being NO:
"tosShownAndAccepted = \(String(describing: tosShownAndAccepted))",
"individual = \(String(describing: individual))",
"company = \(String(describing: company))",
"business_type = \(STPConnectAccountParams.string(from: businessType))",
]
return "<\(props.joined(separator: "; "))>"
}
// MARK: - STPConnectAccountBusinessType
@objc(stringFromBusinessType:)
class func string(from businessType: STPConnectAccountBusinessType) -> String {
switch businessType {
case .individual:
return "individual"
case .company:
return "company"
}
}
}
// MARK: - STPFormEncodable
extension STPConnectAccountParams: STPFormEncodable {
@objc internal var businessTypeString: String {
return STPConnectAccountParams.string(from: businessType)
}
@objc
public class func rootObjectName() -> String? {
return "account"
}
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:tosShownAndAccepted)): "tos_shown_and_accepted",
NSStringFromSelector(#selector(getter:individual)): "individual",
NSStringFromSelector(#selector(getter:company)): "company",
NSStringFromSelector(#selector(getter:businessTypeString)): "business_type",
]
}
}
| 2ee1b5ab511856bb7e93e334e01d33e4 | 36.689441 | 121 | 0.670732 | false | false | false | false |
kamawshuang/iOS---Animation | refs/heads/master | Layer动画(三)/BahamaAir-Completed(三)/BahamaAirLoginScreen/ViewController.swift | apache-2.0 | 1 |
import UIKit
// A delay function
func delay(seconds seconds: Double, completion:()->()) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds ))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion()
}
}
func tintBackgroundColor(layer layer: CALayer, toColor: UIColor) {
let tint = CABasicAnimation(keyPath: "backgroundColor")
tint.fromValue = layer.backgroundColor
tint.toValue = toColor.CGColor
tint.duration = 1.0
layer.addAnimation(tint, forKey: nil)
layer.backgroundColor = toColor.CGColor
}
func roundCorners(layer layer: CALayer, toRadius: CGFloat) {
let round = CABasicAnimation(keyPath: "cornerRadius")
round.fromValue = layer.cornerRadius
round.toValue = toRadius
round.duration = 0.33
layer.addAnimation(round, forKey: nil)
layer.cornerRadius = toRadius
}
class ViewController: UIViewController {
// MARK: IB outlets
@IBOutlet var loginButton: UIButton!
@IBOutlet var heading: UILabel!
@IBOutlet var username: UITextField!
@IBOutlet var password: UITextField!
@IBOutlet var cloud1: UIImageView!
@IBOutlet var cloud2: UIImageView!
@IBOutlet var cloud3: UIImageView!
@IBOutlet var cloud4: UIImageView!
// MARK: further UI
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
let status = UIImageView(image: UIImage(named: "banner"))
let label = UILabel()
let messages = ["Connecting ...", "Authorizing ...", "Sending credentials ...", "Failed"]
var statusPosition = CGPoint.zero
let info = UILabel()
// MARK: view controller methods
override func viewDidLoad() {
super.viewDidLoad()
//set up the UI
loginButton.layer.cornerRadius = 8.0
loginButton.layer.masksToBounds = true
spinner.frame = CGRect(x: -20.0, y: 6.0, width: 20.0, height: 20.0)
spinner.startAnimating()
spinner.alpha = 0.0
loginButton.addSubview(spinner)
status.hidden = true
status.center = loginButton.center
view.addSubview(status)
label.frame = CGRect(x: 0.0, y: 0.0, width: status.frame.size.width, height: status.frame.size.height)
label.font = UIFont(name: "HelveticaNeue", size: 18.0)
label.textColor = UIColor(red: 0.89, green: 0.38, blue: 0.0, alpha: 1.0)
label.textAlignment = .Center
status.addSubview(label)
statusPosition = status.center
info.frame = CGRect(x: 0.0, y: loginButton.center.y + 60.0,
width: view.frame.size.width, height: 30)
info.backgroundColor = UIColor.clearColor()
info.font = UIFont(name: "HelveticaNeue", size: 12.0)
info.textAlignment = .Center
info.textColor = UIColor.whiteColor()
info.text = "Tap on a field and enter username and password"
view.insertSubview(info, belowSubview: loginButton)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
delay(seconds: 5.0, completion: {
print("where are the fields?")
})
let fadeIn = CABasicAnimation(keyPath: "opacity")
fadeIn.fromValue = 0.0
fadeIn.toValue = 1.0
fadeIn.duration = 0.5
fadeIn.fillMode = kCAFillModeBackwards
fadeIn.beginTime = CACurrentMediaTime() + 0.5
cloud1.layer.addAnimation(fadeIn, forKey: nil)
fadeIn.beginTime = CACurrentMediaTime() + 0.7
cloud2.layer.addAnimation(fadeIn, forKey: nil)
fadeIn.beginTime = CACurrentMediaTime() + 0.9
cloud3.layer.addAnimation(fadeIn, forKey: nil)
fadeIn.beginTime = CACurrentMediaTime() + 1.1
cloud4.layer.addAnimation(fadeIn, forKey: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//初始化一个动画群组,设置时间,样式
let formGroup = CAAnimationGroup()
formGroup.duration = 0.5
formGroup.fillMode = kCAFillModeBackwards
//位置动画
let flyRight = CABasicAnimation(keyPath: "position.x")
flyRight.fromValue = -view.bounds.size.width/2
flyRight.toValue = view.bounds.size.width/2
//效果
let fadeFieldIn = CABasicAnimation(keyPath: "opacity")
fadeFieldIn.fromValue = 0.25
fadeFieldIn.toValue = 1.0
//添加
formGroup.animations = [flyRight, fadeFieldIn]
heading.layer.addAnimation(formGroup, forKey: nil)
formGroup.delegate = self
formGroup.setValue("form", forKey: "name")
formGroup.setValue(username.layer, forKey: "layer")
formGroup.beginTime = CACurrentMediaTime() + 0.3
username.layer.addAnimation(formGroup, forKey: nil)
formGroup.setValue(password.layer, forKey: "layer")
formGroup.beginTime = CACurrentMediaTime() + 0.4
password.layer.addAnimation(formGroup, forKey: nil)
let groupAnimation = CAAnimationGroup()
groupAnimation.beginTime = CACurrentMediaTime() + 0.5
groupAnimation.duration = 0.5
groupAnimation.fillMode = kCAFillModeBackwards
groupAnimation.timingFunction = CAMediaTimingFunction(
name: kCAMediaTimingFunctionEaseIn)
let scaleDown = CABasicAnimation(keyPath: "transform.scale")
scaleDown.fromValue = 3.5
scaleDown.toValue = 1.0
let rotate = CABasicAnimation(keyPath: "transform.rotation")
rotate.fromValue = CGFloat(M_PI_4)
rotate.toValue = 0.0
let fade = CABasicAnimation(keyPath: "opacity")
fade.fromValue = 0.0
fade.toValue = 1.0
groupAnimation.animations = [scaleDown, rotate, fade]
loginButton.layer.addAnimation(groupAnimation, forKey: nil)
animateCloud(cloud1.layer)
animateCloud(cloud2.layer)
animateCloud(cloud3.layer)
animateCloud(cloud4.layer)
let flyLeft = CABasicAnimation(keyPath: "position.x")
flyLeft.fromValue = info.layer.position.x +
view.frame.size.width
flyLeft.toValue = info.layer.position.x
flyLeft.duration = 5.0
info.layer.addAnimation(flyLeft, forKey: "infoappear")
let fadeLabelIn = CABasicAnimation(keyPath: "opacity")
fadeLabelIn.fromValue = 0.2
fadeLabelIn.toValue = 1.0
fadeLabelIn.duration = 4.5
info.layer.addAnimation(fadeLabelIn, forKey: "fadein")
username.delegate = self
password.delegate = self
}
// MARK: further methods
@IBAction func login() {
UIView.animateWithDuration(1.5, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.0, options: [], animations: {
self.loginButton.bounds.size.width += 80.0
}, completion: nil)
UIView.animateWithDuration(0.33, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: [], animations: {
self.loginButton.center.y += 60.0
self.spinner.center = CGPoint(x: 40.0, y: self.loginButton.frame.size.height/2)
self.spinner.alpha = 1.0
}, completion: {_ in
self.showMessage(index: 0)
})
let tintColor = UIColor(red: 0.85, green: 0.83, blue: 0.45, alpha: 1.0)
tintBackgroundColor(layer: loginButton.layer, toColor: tintColor)
roundCorners(layer: loginButton.layer, toRadius: 25.0)
let balloon = CALayer()
balloon.contents = UIImage(named: "balloon")!.CGImage
balloon.frame = CGRect(x: -50.0, y: 0.0,
width: 50.0, height: 65.0)
view.layer.insertSublayer(balloon, below: username.layer)
let flight = CAKeyframeAnimation(keyPath: "position")
flight.duration = 12.0
flight.values = [
CGPoint(x: -50.0, y: 0.0),
CGPoint(x: view.frame.width + 50.0, y: 160.0),
CGPoint(x: -50.0, y: loginButton.center.y)
].map { NSValue(CGPoint: $0) }
flight.keyTimes = [0.0, 0.5, 1.0]
balloon.addAnimation(flight, forKey: nil)
balloon.position = CGPoint(x: -50.0, y: loginButton.center.y)
}
func showMessage(index index: Int) {
label.text = messages[index]
UIView.transitionWithView(status, duration: 0.33, options:
[.CurveEaseOut, .TransitionFlipFromBottom], animations: {
self.status.hidden = false
}, completion: {_ in
//transition completion
delay(seconds: 2.0) {
if index < self.messages.count-1 {
self.removeMessage(index: index)
} else {
//reset form
self.resetForm()
}
}
})
}
func removeMessage(index index: Int) {
UIView.animateWithDuration(0.33, delay: 0.0, options: [], animations: {
self.status.center.x += self.view.frame.size.width
}, completion: {_ in
self.status.hidden = true
self.status.center = self.statusPosition
self.showMessage(index: index+1)
})
}
func resetForm() {
let wobble = CAKeyframeAnimation(keyPath: "transform.rotation")
wobble.duration = 0.25
wobble.repeatCount = 4
wobble.values = [0.0, -M_PI_4/4, 0.0, M_PI_4/4, 0.0]
wobble.keyTimes = [0.0, 0.25, 0.5, 0.75, 1.0]
heading.layer.addAnimation(wobble, forKey: nil)
UIView.transitionWithView(status, duration: 0.2, options: .TransitionFlipFromTop, animations: {
self.status.hidden = true
self.status.center = self.statusPosition
}, completion: nil)
UIView.animateWithDuration(0.2, delay: 0.0, options: [], animations: {
self.spinner.center = CGPoint(x: -20.0, y: 16.0)
self.spinner.alpha = 0.0
self.loginButton.bounds.size.width -= 80.0
self.loginButton.center.y -= 60.0
}, completion: {_ in
let tintColor = UIColor(red: 0.63, green: 0.84, blue: 0.35, alpha: 1.0)
tintBackgroundColor(layer: self.loginButton.layer, toColor: tintColor)
roundCorners(layer: self.loginButton.layer, toRadius: 10.0)
})
}
func animateCloud(layer: CALayer) {
//1
let cloudSpeed = 60.0 / Double(view.layer.frame.size.width)
let duration: NSTimeInterval = Double(view.layer.frame.size.width - layer.frame.origin.x) * cloudSpeed
//2
let cloudMove = CABasicAnimation(keyPath: "position.x")
cloudMove.duration = duration
cloudMove.toValue = self.view.bounds.size.width + layer.bounds.width/2
cloudMove.delegate = self
cloudMove.setValue("cloud", forKey: "name")
cloudMove.setValue(layer, forKey: "layer")
layer.addAnimation(cloudMove, forKey: nil)
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
print("animation did finish")
if let name = anim.valueForKey("name") as? String {
if name == "form" {
//form field found
let layer = anim.valueForKey("layer") as? CALayer
anim.setValue(nil, forKey: "layer")
let pulse = CABasicAnimation(keyPath: "transform.scale")
pulse.fromValue = 1.25
pulse.toValue = 1.0
pulse.duration = 0.25
layer?.addAnimation(pulse, forKey: nil)
}
if name == "cloud" {
if let layer = anim.valueForKey("layer") as? CALayer {
anim.setValue(nil, forKey: "layer")
layer.position.x = -layer.bounds.width/2
delay(seconds: 0.5, completion: {
self.animateCloud(layer)
})
}
}
}
}
}
extension ViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(textField: UITextField) {
print(info.layer.animationKeys())
info.layer.removeAnimationForKey("infoappear")
}
}
| 9c4b070600126da312fdf35e240d1a42 | 30.623229 | 132 | 0.666667 | false | false | false | false |
LYM-mg/MGDYZB | refs/heads/master | MGDYZB简单封装版/MGDYZB/Class/Home/Controller/ScanViewController.swift | mit | 1 | //
// ScanViewController.swift
// MGDYZB
//
// Created by i-Techsys.com on 17/4/11.
// Copyright © 2017年 ming. All rights reserved.
// 扫一扫控制器
import UIKit
import AVFoundation
class ScanViewController: UIViewController {
// MARK: - 自定义属性
// MARK: - lazy
/// AVFoundation框架捕获类的中心枢纽,协调输入输出设备以获得数据
fileprivate lazy var session: AVCaptureSession = AVCaptureSession()
/// 图层
fileprivate lazy var preViewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
/// 画形状的layer
fileprivate var shapeLayer: CAShapeLayer?
/// 是否是指定扫描区域
fileprivate lazy var isOpenInterestRect: Bool = true
/// 捕获设备,默认后置摄像头
fileprivate lazy var device: AVCaptureDevice? = AVCaptureDevice.default(for: AVMediaType.video)
/// 扫描界面底部工具栏
fileprivate lazy var scanBottomToolBar: ScanBottomView = {
let sb = ScanBottomView(frame: CGRect(x: 0, y: MGScreenH-100-MGNavHeight, width: MGScreenW, height: 100))
sb.btnClickBlcok = { [unowned self](view, type) in
switch type {
case .flash:
guard let device = self.device else {
self.showInfo(info: "没有输入设备")
return
}
//修改前必须先锁定
try? self.device?.lockForConfiguration()
//必须判定是否有闪光灯,否则如果没有闪光灯会崩溃
if device.hasFlash && device.hasTorch {
if device.flashMode == .off {
device.flashMode = .on
device.torchMode = .on
}else {
device.flashMode = AVCaptureDevice.FlashMode.off
device.torchMode = AVCaptureDevice.TorchMode.off
}
}
device.unlockForConfiguration()
case .photo:
self.takePhotoFromAlbun()
break
case .myqrcode:
self.show(QRCodeViewController(), sender: nil)
break
}
}
return sb
}()
//输入设备
var videoInput: AVCaptureDeviceInput?
/// 输出设备,需要指定他的输出类型及扫描范围
fileprivate var output: AVCaptureMetadataOutput?
var qRScanView: MGScanView?
open var scanStyle: MGScanViewStyle? = MGScanViewStyle()
// MARK: - 生命周期方法
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "扫一扫"
setUpMainView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
perform(#selector(ScanViewController.startScanning), with: nil, afterDelay: 0.3)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
qRScanView?.stopScanAnimation()
session.stopRunning()
}
// 设置框内识别
open func setOpenInterestRect(isOpen:Bool){
isOpenInterestRect = isOpen
}
deinit {
print("MGScanViewController deinit")
}
}
// MARK: - 扫一扫
extension ScanViewController {
fileprivate func setUpMainView() {
view.addSubview(scanBottomToolBar)
self.view.backgroundColor = UIColor.clear
self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
drawScanView()
view.bringSubviewToFront(scanBottomToolBar)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(self.changeCamera))
}
/// 切换摄像头
@objc fileprivate func changeCamera() {
// 0.执行动画
let rotaionAnim = CATransition()
rotaionAnim.type = CATransitionType(rawValue: "oglFlip")
rotaionAnim.subtype = CATransitionSubtype(rawValue: "fromLeft")
rotaionAnim.duration = 0.5
view.layer.add(rotaionAnim, forKey: nil)
// 1.校验videoInput是否有值
guard let videoInput = videoInput else { return }
// 2.获取当前镜头
let position : AVCaptureDevice.Position = videoInput.device.position == .front ? .back : .front
// 3.创建新的input
guard let devices = AVCaptureDevice.devices(for: AVMediaType.video) as? [AVCaptureDevice] else { return }
guard let newDevice = devices.filter({$0.position == position}).first else { return }
guard let newVideoInput = try? AVCaptureDeviceInput(device: newDevice) else { return }
// 4.移除旧输入,添加新输入
session.beginConfiguration()
session.removeInput(videoInput)
session.addInput(newVideoInput)
session.commitConfiguration()
// 5.保存新输入
self.videoInput = newVideoInput
}
open func drawScanView() {
if qRScanView == nil {
qRScanView = MGScanView(frame: self.view.frame,vstyle:scanStyle! )
self.view.addSubview(qRScanView!)
}
qRScanView?.deviceStartReadying(readyStr: "相机启动中...")
}
// 3.开始扫描
@objc open func startScanning() {
// 1.创建会话 //高质量采集率
session.sessionPreset = AVCaptureSession.Preset.high
let authStatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if(authStatus == .restricted || authStatus == .denied) {
self.showInfo(info: "请在iPhone的“设置”-“隐私”-“相机”功能中,找到“XXXX”打开相机访问权限")
return
}
// 2.判断输入能否添加到会话中
if self.videoInput == nil {
guard let input = try? AVCaptureDeviceInput(device: device!) else {
qRScanView?.deviceStopReadying()
self.showInfo(info: "没有相输入设备")
return
}
self.videoInput = input
if session.canAddInput(self.videoInput!) {
session.addInput(self.videoInput!)
}
}
// 3.判断输出能够添加到会话中
if self.output == nil {
self.output = AVCaptureMetadataOutput()
if session.canAddOutput(output!) {
session.addOutput(output!)
}
if isOpenInterestRect {
output?.rectOfInterest = CGRect(x: (124)/MGScreenH, y: ((MGScreenW-220)/2)/MGScreenW, width: 220/MGScreenH, height: 220/MGScreenW)
}
// 设置监听监听输出解析到的数据
output?.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
// 3.1.设置输出能够解析的数据类型
// 注意点: 设置数据类型一定要在输出对象添加到会话之后才能设置
//设置availableMetadataObjectTypes为二维码、条形码等均可扫描,如果想只扫描二维码可设置为
output?.metadataObjectTypes = self.defaultMetaDataObjectTypes()
// Array(arrayLiteral: AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code)
}
// 4.设置图层
preViewLayer.frame = view.bounds
preViewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
view.layer.insertSublayer(preViewLayer, at: 0)
// 5.开始扫描
session.startRunning()
//结束相机等待提示
qRScanView?.deviceStopReadying()
//开始扫描动画
qRScanView?.startScanAnimation()
// 6.拉近镜头,改善条形码读取效果
//修改前必须先锁定
do {
try self.device?.lockForConfiguration()
} catch _ {
NSLog("Error: lockForConfiguration.");
}
// 拉近镜头 放大
self.device?.videoZoomFactor = 1.5
self.device?.unlockForConfiguration()
}
//MARK: ------获取系统默认支持的码的类型
func defaultMetaDataObjectTypes() ->[AVMetadataObject.ObjectType] {
var types =
[AVMetadataObject.ObjectType.qr,
AVMetadataObject.ObjectType.upce,
AVMetadataObject.ObjectType.code39,
AVMetadataObject.ObjectType.code39Mod43,
AVMetadataObject.ObjectType.ean13,
AVMetadataObject.ObjectType.ean8,
AVMetadataObject.ObjectType.code93,
AVMetadataObject.ObjectType.code128,
AVMetadataObject.ObjectType.pdf417,
AVMetadataObject.ObjectType.aztec,
];
if #available(iOS 8.0, *) {
types.append(AVMetadataObject.ObjectType.interleaved2of5)
types.append(AVMetadataObject.ObjectType.itf14)
types.append(AVMetadataObject.ObjectType.dataMatrix)
types.append(AVMetadataObject.ObjectType.interleaved2of5)
types.append(AVMetadataObject.ObjectType.itf14)
types.append(AVMetadataObject.ObjectType.dataMatrix)
}
return types;
}
}
// MARK:- <AVCaptureMetadataOutputObjectsDelegate>的代理方法
extension ScanViewController: AVCaptureMetadataOutputObjectsDelegate {
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
guard let object = metadataObjects.last as? AVMetadataMachineReadableCodeObject else{
print("没有获取到扫描结果")
return
}
// 2.使用预览图层,将corners的点转成坐标系中的点
guard let newObject = preViewLayer.transformedMetadataObject(for: object) as? AVMetadataMachineReadableCodeObject else{
print("没有将corners的点转成坐标系中的点成功")
return
}
// 3.画边框
drawBorder(object: newObject)
// 4.获取扫描结果并且显示出来
if object.stringValue != nil && !object.stringValue!.isEmpty {
qRScanView?.stopScanAnimation()
session.stopRunning()
UIView.animate(withDuration: 0.3, animations: {
// 0.移除之前的图形
self.shapeLayer?.removeFromSuperlayer()
})
// 如果是网址就跳转
if object.stringValue!.contains("http://") || object.stringValue!.contains("https://") {
let url = URL(string: object.stringValue!)
if UIApplication.shared.canOpenURL(url!) {
UIApplication.shared.openURL(url!)
}
} else { // 其他信息 弹框显示
if self.isKind(of: UIViewController.self) || self.isKind(of: UIView.self) {
let alertVc = UIAlertController(title: object.stringValue, message: nil, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "好的", style: .cancel, handler: { (action) in
self.startScanning()
})
alertVc.addAction(cancelAction)
UIApplication.shared.keyWindow?.rootViewController?.present(alertVc, animated: true, completion: nil)
}
}
}
}
/*
* 画边框
*/
private func drawBorder(object: AVMetadataMachineReadableCodeObject) {
// 0.移除之前的图形
self.shapeLayer?.removeFromSuperlayer()
// 1.创建CAShapeLayer(形状类型:专门用于画图)
let shapeLayer = CAShapeLayer()
// 2.设置layer属性
shapeLayer.borderColor = UIColor.orange.cgColor
shapeLayer.borderWidth = 5;
shapeLayer.fillColor = UIColor.red.cgColor
// 3.创建贝塞尔曲线
let path = UIBezierPath()
// 4.给贝塞尔曲线添加对应的点
for i in 0..<object.corners.count {
// 4.1获取每一个点对应的字典
let dict = object.corners[i] as! CFDictionary
let point = CGPoint(dictionaryRepresentation: dict)
// 4.2如果是第一个点,移动到第一个点
if i == 0 {
path.move(to: point!)
continue
}
// 4.3如果是其他的点,则添加线
path.addLine(to: point!)
}
// 5闭合path路径
path.close()
// 6.给shapeLayer添加路径
shapeLayer.path = path.cgPath
// 7.将shapeLayer添加到其他视图上
preViewLayer.addSublayer(shapeLayer)
// 8.保存shapeLayer
self.shapeLayer = shapeLayer
}
}
// MARK: - 扫描系统相片中二维码和录制视频
extension ScanViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
@objc fileprivate func takePhotoFromAlbun() {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (action) in }
let photoAction = UIAlertAction(title: "相册", style: .default) { (action) in
print(action)
self.openCamera(.photoLibrary)
}
alertController.addAction(cancelAction)
alertController.addAction(photoAction)
// 判断是否为pad 弹出样式
present(alertController, animated: true, completion: nil)
}
/**
* 打开照相机/打开相册
*/
func openCamera(_ type: UIImagePickerController.SourceType,title: String? = "") {
if !UIImagePickerController.isSourceTypeAvailable(type) {
self.showInfo(info: "Camera不可用")
return
}
let ipc = UIImagePickerController()
ipc.sourceType = type
ipc.delegate = self
present(ipc, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
getQRCodeInfo(image: image!)
picker.dismiss(animated: true, completion: nil)
}
/// 取得图片中的信息
fileprivate func getQRCodeInfo(image: UIImage) {
// 1.创建扫描器
guard let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: nil) else { return }
// 2.扫描结果
guard let ciImage = CIImage(image: image) else { return }
let features = detector.features(in: ciImage)
// 3.遍历扫描结果
for f in features {
guard let feature = f as? CIQRCodeFeature else { return }
if (feature.messageString?.isEmpty)! {
return
}
// 如果是网址就跳转
if feature.messageString!.contains("http://") || feature.messageString!.contains("https://") {
let url = URL(string: feature.messageString!)
if UIApplication.shared.canOpenURL(url!) {
UIApplication.shared.openURL(url!)
}
} else { // 其他信息 弹框显示
debugPrint(feature.messageString ?? "")
}
}
}
}
///// 定位扫描框在哪个位置 定位扫描框在屏幕正中央,并且宽高为200的正方形
//fileprivate lazy var scanView: UIView = {
// let v = UIView(frame: CGRect(x: (MGScreenW-200)/2, y: (self.view.frame.size.height-200)/2, width: 200, height: 200))
// return v
//}()
///// 设置扫描界面(包括扫描界面之外的部分置灰,扫描边框等的设置),后面设置
//fileprivate lazy var clearView: UIView = { [unowned self] in
// //定位扫描框在屏幕正中央,并且宽高为200的正方形
// let v = UIView(frame: self.view.frame)
// return v
//}()
| e7d8644e78f36a5ed1852b5b84fd04fa | 35.317191 | 156 | 0.591973 | false | false | false | false |
GabrielAraujo/VaporMongo | refs/heads/master | Sources/App/Models/Object.swift | mit | 1 | //
// Object.swift
// VaporMongo
//
// Created by Gabriel Araujo on 14/11/16.
//
//
import Vapor
import Fluent
import Foundation
final class Object: Model {
var id: Node?
var type: String?
var data: Node?
var exists: Bool = false
init(type:String, data: Node) {
self.id = UUID().uuidString.makeNode()
self.type = type
self.data = data
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
type = try node.extract("type")
data = try node.extract("data")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"type": type,
"data" : data
])
}
}
extension Object {
/**
This will automatically fetch from database, using example here to load
automatically for example. Remove on real models.
*/
public convenience init?(from type: String, data: Node) throws {
self.init(type: type, data: data)
}
}
extension Object: Preparation {
static func prepare(_ database: Database) throws {
//
}
static func revert(_ database: Database) throws {
//
}
}
| 046c1ce3b4f05d6c06352631435a0219 | 20.206897 | 76 | 0.566667 | false | false | false | false |
wireapp/wire-ios-data-model | refs/heads/develop | Source/Model/Conversation/ZMConversation+Confirmations.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
extension ZMConversation {
@NSManaged dynamic public var hasReadReceiptsEnabled: Bool
/// Confirm unread received messages as read.
///
/// - Parameters:
/// - range: Unread messages received within this date range will be confirmed as read.
@discardableResult
func confirmUnreadMessagesAsRead(in range: ClosedRange<Date>) -> [ZMClientMessage] {
let unreadMessagesNeedingConfirmation = unreadMessages(in: range).filter(\.needsReadConfirmation)
var confirmationMessages: [ZMClientMessage] = []
for messages in unreadMessagesNeedingConfirmation.partition(by: \.sender).values {
guard
!messages.isEmpty,
let confirmation = Confirmation(messageIds: messages.compactMap(\.nonce), type: .read)
else {
continue
}
do {
let confirmationMessage = try appendClientMessage(with: GenericMessage(content: confirmation), expires: false, hidden: true)
confirmationMessages.append(confirmationMessage)
} catch {
Logging.messageProcessing.warn("Failed to append confirmation. Reason: \(error.localizedDescription)")
}
}
return confirmationMessages
}
@discardableResult @objc
public func appendMessageReceiptModeChangedMessage(fromUser user: ZMUser, timestamp: Date, enabled: Bool) -> ZMSystemMessage {
let message = appendSystemMessage(
type: enabled ? .readReceiptsEnabled : .readReceiptsDisabled,
sender: user,
users: [],
clients: nil,
timestamp: timestamp
)
if isArchived && mutedMessageTypes == .none {
isArchived = false
}
return message
}
@discardableResult @objc
public func appendMessageReceiptModeIsOnMessage(timestamp: Date) -> ZMSystemMessage {
let message = appendSystemMessage(
type: .readReceiptsOn,
sender: creator,
users: [],
clients: nil,
timestamp: timestamp
)
return message
}
}
| b9cd896bf7e2b899c8ca02a733e0f116 | 32.811765 | 140 | 0.650661 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | packages/TGUIKit/Sources/BadgeNode.swift | gpl-2.0 | 1 | //
// BadgeNode.swift
// TGUIKit
//
// Created by keepcoder on 11/10/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import AppKit
public class BadgeNode: Node {
private var textLayout:(TextNodeLayout, TextNode)
public var fillColor:NSColor {
didSet {
if fillColor != oldValue {
self.view?.setNeedsDisplay()
}
}
}
deinit {
var bp:Int = 0
bp += 1
}
override public func draw(_ layer: CALayer, in ctx: CGContext) {
if let view = view {
ctx.setFillColor(fillColor.cgColor)
ctx.round(self.size, self.size.height/2.0)
ctx.fill(layer.bounds)
let focus = view.focus(textLayout.0.size)
textLayout.1.draw(focus, in: ctx, backingScaleFactor: view.backingScaleFactor, backgroundColor: view.backgroundColor)
}
}
public var additionSize: NSSize = NSMakeSize(8, 7)
public init(_ attributedString:NSAttributedString, _ fillColor:NSColor) {
textLayout = TextNode.layoutText(maybeNode: nil, attributedString, nil, 1, .middle, NSMakeSize(CGFloat.greatestFiniteMagnitude, CGFloat.greatestFiniteMagnitude), nil, false, .left)
self.fillColor = fillColor
super.init()
size = NSMakeSize(textLayout.0.size.width + additionSize.width, textLayout.0.size.height + additionSize.height)
size = NSMakeSize(max(size.height,size.width), size.height)
}
}
| ec85dcdc90db14067d92085e71fd9429 | 27.781818 | 189 | 0.602653 | false | false | false | false |
MR-Zong/ZGResource | refs/heads/master | Project/FamilyEducationApp-master/家教/LoginViewController.swift | gpl-2.0 | 1 | //
// LoginViewController.swift
// 家教
//
// Created by goofygao on 15/11/14.
// Copyright © 2015年 goofyy. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController,UINavigationControllerDelegate,UITextFieldDelegate {
let avaterImageView = UIImageView()
let loginTextBG = UIImageView()
let loginUserNameTextField = UITextField()
let passwordTextField = UITextField()
let loginButton = UIButton()
var acitivityView = UIActivityIndicatorView()
var alertView = UIAlertView()
let defaultValue = NSUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
loginUserNameTextField.delegate = self
passwordTextField.delegate = self
self.navigationController?.delegate = self
self.navigationController?.navigationBarHidden = true
self.navigationController?.toolbarHidden = true
self.initView()
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerAction", userInfo: nil, repeats: true)
// let time = NSTimer(timeInterval: 2, target: self, selector: "timerAction", userInfo: nil, repeats: true)
}
//initView
func initView() {
avaterImageView.bounds.size = CGSizeMake(100, 100)
avaterImageView.center = CGPointMake(DeviceData.width/2, 100)
avaterImageView.image = UIImage(named: "touxiang.png")
avaterImageView.layer.cornerRadius = 50
avaterImageView.layer.masksToBounds = true
avaterImageView.layer.borderWidth = 5
avaterImageView.layer.borderColor = UIColor(white: 0.5, alpha: 0.7).CGColor
self.view.addSubview(avaterImageView)
loginTextBG.bounds.size = CGSizeMake(DeviceData.width + 20, 100)
loginTextBG.center = CGPointMake(DeviceData.width/2, 240)
loginTextBG.alpha = 0.8
loginTextBG.image = UIImage(named: "bg_login.png")
self.view.addSubview(loginTextBG)
loginUserNameTextField.frame = CGRectMake(40, 200, DeviceData.width - 80, 30)
loginUserNameTextField.placeholder = "手机号/邮箱"
loginUserNameTextField.borderStyle = UITextBorderStyle.None
loginUserNameTextField.textAlignment = NSTextAlignment.Center
loginUserNameTextField.keyboardType = UIKeyboardType.EmailAddress
loginUserNameTextField.font = UIFont.systemFontOfSize(14)
loginUserNameTextField.text = "goofyyivan"
self.view.addSubview(loginUserNameTextField)
passwordTextField.frame = CGRectMake(40, 250, DeviceData.width - 80, 30)
passwordTextField.placeholder = "密码"
passwordTextField.text = "123456"
passwordTextField.borderStyle = UITextBorderStyle.None
passwordTextField.textAlignment = NSTextAlignment.Center
passwordTextField.font = UIFont.systemFontOfSize(14)
passwordTextField.keyboardType = UIKeyboardType.EmailAddress
passwordTextField.secureTextEntry = true
self.view.addSubview(passwordTextField)
loginButton.frame = CGRectMake(20, 300, DeviceData.width - 40, 50)
loginButton.setBackgroundImage(UIImage(named: "bt_login.png"), forState: UIControlState.Normal)
loginButton.addTarget(self, action: "loginAction", forControlEvents: UIControlEvents.TouchDown)
self.view.addSubview(loginButton)
acitivityView.frame = CGRectMake(0, 0, 30, 30)
acitivityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.White
acitivityView.center = CGPointMake(60, loginButton.center.y)
// acitivityView.becomeFirstResponder()
self.view.addSubview(acitivityView)
// acitivityView.startAnimating()
}
func loginAction() {
print(loginUserNameTextField.text)
if loginUserNameTextField.text == "" || passwordTextField.text == "" {
self.alertView = UIAlertView(title: "提示", message: "亲好像还没有登陆哦", delegate: self, cancelButtonTitle: "OK")
alertView.show()
} else {
acitivityView.startAnimating()
let manager = AFHTTPRequestOperationManager()
manager.responseSerializer.acceptableContentTypes = NSSet(object: "text/html") as Set<NSObject>
let params:NSDictionary = ["password":passwordTextField.text!,"username":loginUserNameTextField.text!]
print(params)
manager.POST("http://115.29.54.119:888/Post/login", parameters: params, success: { (operation, response) -> Void in
let responseDic = response as? NSDictionary
let accessToken:String? = responseDic?["access_token"] as? String
self.defaultValue.setValue(accessToken, forKey: "access_token")
print(accessToken)
if(responseDic == nil) {
self.alertView = UIAlertView(title: "提示", message: "亲好像还没注册哦", delegate: self, cancelButtonTitle: "OK")
self.alertView.show()
self.acitivityView.stopAnimating()
} else {
let storyBoadrd = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let homePageNavigationController:UINavigationController = storyBoadrd.instantiateViewControllerWithIdentifier("homePage") as! UINavigationController
self.presentViewController(homePageNavigationController, animated: true, completion: nil)
}
}) { (operation, error) -> Void in
}
}
}
func timerAction() {
UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.avaterImageView.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI_2), 0, 1, 0)
}) { (bool:Bool) -> Void in
UIView.animateWithDuration(1) { () -> Void in
self.avaterImageView.layer.transform = CATransform3DMakeRotation(CGFloat(-M_PI_4), 0, 1, 0)
}
}
}
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
if viewController == self {
self.navigationController?.navigationBarHidden = true
}
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return true
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
loginUserNameTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
loginUserNameTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
return true
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
loginUserNameTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
}
}
| d9aaf377754e144563cd417064e35679 | 40.333333 | 168 | 0.654338 | false | false | false | false |
bugitapp/bugit | refs/heads/master | bugit/View Controllers/EditorViewController.swift | apache-2.0 | 1 | //
// EditorViewController.swift
// bugit
//
// Created by Ernest on 11/12/16.
// Copyright © 2016 BugIt App. All rights reserved.
//
import UIKit
import AVFoundation
enum ToolsInTray: Int {
case Arrow
case Text
case Circle
case Square
case Freehand
case Blur
case Audio
}
class EditorViewController: UIViewController, UIScrollViewDelegate {
//@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var canvasImageView: UIImageView!
var scaledCanvasImage: UIImage!
@IBOutlet weak var trayViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var trayViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var toolButtonView: HorizontalButtonView!
let colorArray = [ 0x000000, 0xfe0000, 0xff7900, 0xffb900, 0xffde00, 0xfcff00, 0xd2ff00, 0x05c000, 0x00c0a7, 0x0600ff, 0x6700bf, 0x9500c0, 0xbf0199, 0xffffff ]
@IBOutlet weak var selectedColorView: UIView!
@IBOutlet weak var colorSlider: UISlider!
@IBOutlet weak var colorbarImageView: UIImageView!
var textEntryView: UITextView!
var screenshotAssetModel: ScreenshotAssetModel?
var audioFilename: URL?
var panBegan = CGPoint(x:0, y:0)
var panEnded = CGPoint(x:0, y:0)
var selectedColor: UIColor = UIColor.red
var selectedButtonState: Int = 0
@IBOutlet weak var trayView: UIView!
@IBOutlet weak var trayArrowButton: UIButton!
//@IBOutlet weak var trayToolsView: UIView!
@IBOutlet weak var trayArrowImageView: UIImageView!
let travViewClosedPeekOutDistance: CGFloat = 30
//var trayOriginalCenter: CGPoint!
//var trayDownOffset: CGFloat!
//var trayUp: CGPoint!
//var trayDown: CGPoint!
var dragArrowLayer = CAShapeLayer()
var dragDrawLayer = CAShapeLayer()
var selectedTool = ToolsInTray(rawValue: 0) // Arrow tool by default
var path: UIBezierPath = UIBezierPath()
var shapeLayer: CAShapeLayer!
var isTrayOpen: Bool = true
var bottomConstraintStartY: CGFloat = 0.0
var trayTravelDiff: CGFloat = 0.0
static let inset: CGFloat = 2.0
let textEntryViewInset = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
/*
override func viewWillAppear(_ animated: Bool) {
// Hide the navigation bar on the this view controller
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
// Show the navigation bar on other view controllers
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
*/
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// TODO: Add image from Gallery
//canvasImageView.image = UIImage.init(named: "sample")
navigationItem.title = "Annotate Screenshot"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
dlog("screenshot: \(screenshotAssetModel)")
// self.scrollView.minimumZoomScale = 0.5;
// self.scrollView.maximumZoomScale = 6.0;
// self.scrollView.contentSize = canvasImageView.frame.size;
// self.scrollView.delegate = self;
canvasImageView.image = screenshotAssetModel?.screenshotImage
//canvasImageView.addBlurEffect()
//canvasImageView.image = canvasImageView.image?.pixellated(scale: 20)
// Gesture overload if we use swipes
//navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Collage"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(goToGallery))
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Export"), landscapeImagePhone: nil, style: .done, target: self, action: #selector(goToExport))
/*
// Gesture: Go to Gallery
let leftEdgePan = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(goToGallery))
leftEdgePan.edges = .left
view.addGestureRecognizer(leftEdgePan)
// Gesture: Go to Export
let rightEdgePan = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(goToExport))
rightEdgePan.edges = .right
view.addGestureRecognizer(rightEdgePan)
*/
// TODO: Slide up to bring up Settings?
// TODO: Control Arrow settings & color
// Gesture: Go back / Track
let topEdgePan = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(trashCanvas))
topEdgePan.edges = .top
view.addGestureRecognizer(topEdgePan)
// Gesture: Pan to track where arrow should go
let drawPan = UIPanGestureRecognizer(target: self, action: #selector(onPan))
view.addGestureRecognizer(drawPan)
// Gesture: Tap to draw shapes
let drawTap = UITapGestureRecognizer(target: self, action: #selector(didTap))
self.view.addGestureRecognizer(drawTap)
setupToolbox()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.closeMenu()
trayTravelDiff = trayViewHeightConstraint.constant - travViewClosedPeekOutDistance
dlog("trayTravelDiff: \(trayTravelDiff)")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
dlog("screenshot scale: \(self.screenshotAssetModel?.screenshotImage?.scale)")
let scaledCanvas = scaleImageToImageAspectFit(imageView: self.canvasImageView)
self.scaledCanvasImage = scaledCanvas
}
func setupToolbox() {
print("selectedTool = \(selectedTool)")
toolButtonView.tag = 2
toolButtonView.buttonDelegate = self
toolButtonView.selectedColor = selectedColor
selectedColorView.backgroundColor = selectedColor
colorSlider.thumbTintColor = selectedColor
let point = CGPoint(x:100, y:100)
let tvRect = CGRect(origin: point, size: CGSize(width: 128.0, height: 128.0))
textEntryView = UITextView(frame: tvRect)
let cancelItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelTextEntry(sender:)))
let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTextEntry(sender:)))
let spaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let toolbar = UIToolbar(frame: CGRect.zero)
toolbar.items = [cancelItem, spaceItem, doneItem]
toolbar.sizeToFit()
textEntryView.inputAccessoryView = toolbar
textEntryView.backgroundColor = UIColor.clear
textEntryView.isHidden = true
textEntryView.textColor = selectedColor
textEntryView.font = defaultBodyFont
textEntryView.keyboardType = .default
textEntryView.autocapitalizationType = .sentences
textEntryView.autocorrectionType = .no
textEntryView.spellCheckingType = .no
textEntryView.textContainerInset = textEntryViewInset
textEntryView.layer.borderColor = UIColor.black.cgColor
textEntryView.layer.borderWidth = 2.0
textEntryView.layer.cornerRadius = 2.0
canvasImageView.addSubview(textEntryView)
trayView.layer.shadowOffset = CGSize(0, 3);
trayView.layer.shadowRadius = 3;
trayView.layer.shadowOpacity = 0.5;
trayView.layer.borderWidth = 2
trayView.layer.borderColor = UIColor.black.cgColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Actions
@IBAction func trashCanvas(_ sender: UIScreenEdgePanGestureRecognizer) {
if sender.state == .recognized {
dismiss(animated: true, completion: nil)
}
}
@IBAction func goToGallery() {
//self.performSegue(withIdentifier: "GallerySegue", sender: self)
dlog("diabled")
}
@IBAction func goToExport() {
let jiraMgr = JiraManager(domainName: nil, username: nil, password: nil)
if !jiraMgr.userLoggedIn() {
self.performSegue(withIdentifier: "LoginSegue", sender: self)
}
else {
self.performSegue(withIdentifier: "CreateIssueSegue", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CreateIssueSegue" {
// Get a reference to the detail view controller
let destinationViewController = segue.destination as! CreateIssueViewController
// Pass the flat canvas to export
screenshotAssetModel?.editedImage = takeSnapshotOfView(view: canvasImageView)
destinationViewController.screenshotAssetModel = self.screenshotAssetModel
destinationViewController.audioFilename = self.audioFilename
}
}
// MARK: - Gestures
@IBAction func onCanvasViewPinch(_ sender: UIPinchGestureRecognizer) {
dlog("sender.scale: \(sender.scale)")
canvasImageView.transform = canvasImageView.transform.scaledBy(x: sender.scale, y: sender.scale)
sender.scale = 1
}
// Using Simultaneous Gesture Recognizers
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
@IBAction func onTrayPanGesture(_ sender: UIPanGestureRecognizer) {
//let location = sender.location(in: view)
let velocity = sender.velocity(in: view)
let translation = sender.translation(in: view)
if sender.state == .began {
//trayOriginalCenter = trayView.center
bottomConstraintStartY = self.trayViewBottomConstraint.constant
//trayArrowImageView.transform = CGAffineTransform(rotationAngle: CGFloat(180 * M_PI / 180))
} else if sender.state == .changed {
//trayView.center = CGPoint(x: trayOriginalCenter.x, y: trayOriginalCenter.y + translation.y)
let newBottomConstraintY = bottomConstraintStartY - translation.y
if newBottomConstraintY <= 0 && newBottomConstraintY >= -self.trayTravelDiff {
self.trayViewBottomConstraint.constant = newBottomConstraintY
//let rotation = arrowRotationForTrayPan(translation: translation, velocity: velocity)
//self.trayArrowImageView.transform = CGAffineTransform(rotationAngle: rotation)
dlog("Gesture change at: \(translation), newConstraintY: \(newBottomConstraintY)")
}
} else if sender.state == .ended {
//trayArrowImageView.transform = CGAffineTransform(rotationAngle: CGFloat(0 * M_PI / 180))
if velocity.y > 0 {
self.closeMenu()
/*
UIView.animate(withDuration:0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options:[] ,
animations: { () -> Void in
self.trayView.center = self.trayDown
}, completion: nil)
*/
} else {
/*
UIView.animate(withDuration:0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options:[] ,
animations: { () -> Void in
self.trayView.center = self.trayUp
}, completion: nil)
*/
self.openMenu()
}
}
}
@IBAction func onTrayArrowButtonTapped(sender: AnyObject) {
dlog("")
if isTrayOpen {
closeMenu()
}
else {
openMenu()
}
}
func closeMenu() {
if !isTrayOpen {
return
}
let options: UIViewAnimationOptions = .curveEaseOut
UIView.animate(withDuration: 0.3, delay: 0, options: options,
animations: { () -> Void in
self.trayViewBottomConstraint.constant = (-self.trayViewHeightConstraint.constant + self.travViewClosedPeekOutDistance)
self.trayArrowImageView.transform = CGAffineTransform(rotationAngle: .pi)
self.view.layoutIfNeeded()
},
completion: { (done: Bool) -> Void in
self.isTrayOpen = false
dlog("trayView bottom constraint: \(self.trayViewBottomConstraint.constant)")
})
}
func openMenu() {
if isTrayOpen {
return
}
let options: UIViewAnimationOptions = .curveEaseInOut
UIView.animate(withDuration: 0.3, delay: 0, options: options,
animations: { () -> Void in
self.trayViewBottomConstraint.constant = 0
self.trayArrowImageView.transform = CGAffineTransform(rotationAngle: 0.0)
self.view.layoutIfNeeded()
},
completion: { (done: Bool) -> Void in
self.isTrayOpen = true
dlog("trayView bottom constraint: \(self.trayViewBottomConstraint.constant)")
})
}
// MARK: - Toolbox
// MARK: - Draw
func takeSnapshotOfView(view:UIView) -> UIImage? {
UIGraphicsBeginImageContext(CGSize(width: view.frame.size.width, height: view.frame.size.height))
view.drawHierarchy(in: CGRect(x: 0.0, y: 0.0, width: view.frame.size.width, height: view.frame.size.height), afterScreenUpdates: true) // <-- TODO? required?
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func scaleImageToImageAspectFit(imageView: UIImageView) -> UIImage? {
if let img = imageView.image {
dlog("origImageSize: \(img.size)")
let rect = AVMakeRect(aspectRatio: img.size, insideRect: imageView.bounds)
dlog("scaledImageRect: \(rect)")
let scaledImage = img.simpleScale(newSize: rect.size)
dlog("scaledImage: \(scaledImage)")
return scaledImage
}
return nil
}
@IBAction func didTap(_ sender: UITapGestureRecognizer) {
print("didTap.sender.state = \(sender.state)")
print("didTap.selectedTool = \(selectedTool)")
let point = sender.location(in: canvasImageView)
// Text
if selectedTool == ToolsInTray.Text {
textEntryView.textColor = selectedColor
textEntryView.frame.origin = point
textEntryView.isHidden = false
textEntryView.becomeFirstResponder()
}
// Square
else if selectedTool == ToolsInTray.Square {
let shapeView = ShapeView(origin: point, paletteColor: self.selectedColor, shapeType: ShapeType.Square)
self.canvasImageView.addSubview(shapeView)
}
// Circle
else if selectedTool == ToolsInTray.Circle {
let shapeView = ShapeView(origin: point, paletteColor: self.selectedColor, shapeType: ShapeType.Circle)
self.canvasImageView.addSubview(shapeView)
}
// Blur
else if selectedTool == ToolsInTray.Blur {
if let origImageSize = self.screenshotAssetModel?.screenshotImage?.size {
let scaledRect = AVMakeRect(aspectRatio: origImageSize, insideRect: self.canvasImageView.bounds)
let w:CGFloat = 100.0
let h:CGFloat = 75.0
let x:CGFloat = point.x - w/2.0
let y:CGFloat = point.y - h/2.0
if x >= scaledRect.origin.x {
let placedRect = CGRect(x: x, y: y, width: w, height: h)
let pimageView = PixelatedImageView(frame: placedRect, image: scaledCanvasImage, regionSize: placedRect.size, containerBounds: self.canvasImageView.bounds)
pimageView.applyPixelation()
self.canvasImageView.addSubview(pimageView)
}
}
}
// Audio
else if selectedTool == ToolsInTray.Audio {
// Show Audio controls on Tap?
}
}
func cancelTextEntry(sender: AnyObject) {
dlog("cancel")
textEntryView.isHidden = true
textEntryView.resignFirstResponder()
textEntryView.text = nil
}
func doneTextEntry(sender: AnyObject) {
//food for thot http://stackoverflow.com/questions/746670/how-to-lose-margin-padding-in-uitextview
let contentSize = textEntryView.contentSize
dlog("done, contentSize: \(contentSize)")
textEntryView.isHidden = true
textEntryView.resignFirstResponder()
let text = textEntryView.text
textEntryView.text = nil
if let entryText = text {
var point = textEntryView.frame.origin
point.x += textEntryView.textContainerInset.left + textEntryView.textContainer.lineFragmentPadding
point.y += textEntryView.textContainerInset.left
let textView = TextView(origin: point, size: contentSize, paletteColor: self.selectedColor)
let newTextLayer = textView.generateText(drawText: entryText)
textView.layer.addSublayer(newTextLayer)
self.canvasImageView.addSubview(textView)
}
}
@IBAction func onPan(_ sender: UIPanGestureRecognizer) {
print("panned")
print("onPan.sender.state = \(sender.state)")
//let translation = sender.translation(in: view)
let point = sender.location(in: canvasImageView) as CGPoint
//print("point = \(point)")
if sender.state == UIGestureRecognizerState.began {
print("onPan.began")
panBegan = point as CGPoint
print("panBegan = \(panBegan)")
if selectedTool == ToolsInTray.Freehand {
drawStartAtPoint(point: point)
}
} else if sender.state == .changed {
print("onPan.changed")
if selectedTool == ToolsInTray.Arrow {
// draw the arrow as the gesture changes so user can see where they will be drawing the arrow
// http://stackoverflow.com/questions/27117060/how-to-transform-a-line-during-pan-gesture-event
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
drawArrow(from: panBegan, to: point, layer: dragArrowLayer)
CATransaction.commit()
}
if selectedTool == ToolsInTray.Freehand {
drawContinueAtPoint(point: point)
}
} else if sender.state == UIGestureRecognizerState.ended {
print("onPan.ended")
if selectedTool == ToolsInTray.Arrow {
panEnded = point as CGPoint
print("tapEnded = \(panEnded)")
print("tapBegan = \(panBegan)")
// Draw Arrow
drawArrow(from: panBegan, to: panEnded, layer: nil)
}
}
}
// MARK: Tracking an Arrow
func drawArrow(from: CGPoint, to: CGPoint, layer: CAShapeLayer?) {
// TODO: Should be set from Settings?
let tailWidth = 10 as CGFloat
let headWidth = 25 as CGFloat
let headLength = 40 as CGFloat
// CGPoint(x:10, y:10)
// CGPoint(x:200, y:10)
let arrow = UIBezierPath.arrow(from: from, to: to, tailWidth: tailWidth, headWidth: headWidth, headLength: headLength)
var shapeLayer: CAShapeLayer
shapeLayer = layer == nil ? CAShapeLayer() : layer!
shapeLayer.path = arrow.cgPath
//shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.fillColor = selectedColor.cgColor // this is set by each pencil tap
canvasImageView.layer.addSublayer(shapeLayer)
}
// MARK: Tracing a Line
func drawStartAtPoint(point: CGPoint) {
path = UIBezierPath()
path.move(to: point)
shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = selectedColor.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor // Note this has to be clear otherwise fill will form webs in between points
shapeLayer.lineWidth = 4.0 // TODO: Control the width of this line
canvasImageView.layer.addSublayer(shapeLayer)
}
func drawContinueAtPoint(point: CGPoint) {
path.addLine(to: point)
shapeLayer.path = path.cgPath
}
// MARK: Drawing a path
func drawPoint() {
self.selectedColor.setStroke()
self.path.lineWidth = 10.0 // TODO: Allow manipulation
self.path.lineCapStyle = .round // TODO: Allow change to different styles
self.path.stroke()
}
func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
self.selectedColor.setStroke()
self.path.lineWidth = 10.0 // TODO: Allow manipulation
self.path.lineCapStyle = .round // TODO: Allow change to different styles
self.path.stroke()
context?.addPath(self.path as! CGPath)
}
// MARK: Allows pinching of photo to resize it
//func viewForZooming(in scrollView: UIScrollView) -> UIView? {
// return self.canvasImageView
//}
//func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
// empty
//}
@IBAction func sliderChanged(sender: AnyObject) {
let colorValue = colorArray[Int(colorSlider.value)]
let selectedColor = UIColor(netHex: colorValue)
selectedColorView.backgroundColor = selectedColor
colorSlider.thumbTintColor = selectedColor
self.selectedColor = selectedColor
toolButtonView.selectedColor = selectedColor
toolButtonView.refreshButtonColors(selectedButtonState: selectedButtonState)
}
}
extension EditorViewController: HorizontalButtonViewDelegate {
internal func onHButtonPressed(buttonView: HorizontalButtonView, button: UIButton) {
dlog("btnView: \(buttonView.tag), buttontag: \(button.tag)")
selectedTool = ToolsInTray(rawValue: button.tag)
selectedButtonState = button.tag
}
internal func onAudioRecorded(audioFilename: URL) {
dlog("audioFilename: \(audioFilename)")
self.audioFilename = audioFilename
}
}
| 9f601d3464ac84d8ff4cd9906fe27303 | 37.900166 | 180 | 0.61906 | false | false | false | false |
peaks-cc/iOS11_samplecode | refs/heads/master | chapter_10/BookReader/BookReader/SearchResultsCell.swift | mit | 1 | //
// SearchResultsCell.swift
// BookReader
//
// Created by Kishikawa Katsumi on 2017/07/03.
// Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//
import UIKit
class SearchResultsCell: UITableViewCell {
var section: String? = nil {
didSet {
sectionLabel.text = section
}
}
var page: String? = nil {
didSet {
pageNumberLabel.text = page
}
}
var resultText: String? = nil
var searchText: String? = nil
@IBOutlet private weak var sectionLabel: UILabel!
@IBOutlet private weak var pageNumberLabel: UILabel!
@IBOutlet private weak var resultTextLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
sectionLabel.font = UIFont.preferredFont(forTextStyle: .headline)
pageNumberLabel.textColor = .gray
pageNumberLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
resultTextLabel.font = UIFont.preferredFont(forTextStyle: .body)
}
override func layoutSubviews() {
super.layoutSubviews()
let highlightRange = (resultText! as NSString).range(of: searchText!, options: .caseInsensitive)
let attributedString = NSMutableAttributedString(string: resultText!)
attributedString.addAttributes([.font: UIFont.boldSystemFont(ofSize: resultTextLabel.font.pointSize)], range: highlightRange)
resultTextLabel.attributedText = attributedString
}
}
| f6ea3b6e980062a3d60881ebcf0e6cad | 31.4 | 133 | 0.684499 | false | false | false | false |
Oscareli98/Moya | refs/heads/master | Demo/Pods/RxSwift/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift | mit | 4 | //
// AnonymousDisposable.swift
// Rx
//
// Created by Krunoslav Zaher on 2/15/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
public class AnonymousDisposable : DisposeBase, Cancelable {
public typealias DisposeAction = () -> Void
var lock = Lock()
var disposeAction: DisposeAction?
public var disposed: Bool {
get {
return lock.calculateLocked {
return self.disposeAction == nil
}
}
}
public init(_ disposeAction: DisposeAction) {
self.disposeAction = disposeAction
super.init()
}
public func dispose() {
let toDispose: DisposeAction? = lock.calculateLocked {
var action = self.disposeAction
self.disposeAction = nil
return action
}
if let toDispose = toDispose {
toDispose()
}
}
} | 4dde71b879a2f458dccce997f7e5381d | 21.926829 | 62 | 0.576145 | false | false | false | false |
doo/das-quadrat | refs/heads/develop | Source/Shared/Authorizer.swift | bsd-2-clause | 1 | //
// Authorizer.swift
// Quadrat
//
// Created by Constantine Fry on 09/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
protocol AuthorizationDelegate : class {
func userDidCancel()
func didReachRedirectURL(redirectURL: NSURL)
}
class Authorizer: AuthorizationDelegate {
var redirectURL : NSURL
var authorizationURL : NSURL
var completionHandler: ((String?, NSError?) -> Void)?
let keychain: Keychain
var shouldControllNetworkActivityIndicator = false
convenience init(configuration: Configuration) {
let baseURL = configuration.server.oauthBaseURL
let parameters = [
Parameter.client_id : configuration.client.id,
Parameter.redirect_uri : configuration.client.redirectURL,
Parameter.v : configuration.version,
Parameter.response_type : "token"
]
let authorizationURL = Parameter.buildURL(NSURL(string: baseURL)!, parameters: parameters)
let redirectURL = NSURL(string: configuration.client.redirectURL)
if redirectURL == nil {
fatalError("There is no redirect URL.")
}
let keychain = Keychain(configuration: configuration)
self.init(authorizationURL: authorizationURL, redirectURL: redirectURL!, keychain: keychain)
self.shouldControllNetworkActivityIndicator = configuration.shouldControllNetworkActivityIndicator
self.cleanupCookiesForURL(authorizationURL)
}
init(authorizationURL: NSURL, redirectURL: NSURL, keychain:Keychain) {
self.authorizationURL = authorizationURL
self.redirectURL = redirectURL
self.keychain = keychain
}
// MARK: - Delegate methods
func userDidCancel() {
let error = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil)
self.finilizeAuthorization(nil, error: error)
}
func didReachRedirectURL(redirectURL: NSURL) {
println("redirectURL" + redirectURL.absoluteString!)
let parameters = self.extractParametersFromURL(redirectURL)
self.finilizeAuthorizationWithParameters(parameters)
}
// MARK: - Finilization
func finilizeAuthorizationWithParameters(parameters: Parameters) {
var error: NSError?
if let errorString = parameters["error"] {
error = NSError.quadratOauthErrorForString(errorString)
}
self.finilizeAuthorization(parameters["access_token"], error: error)
}
func finilizeAuthorization(accessToken: String?, error: NSError?) {
var resultError = error
var result = accessToken
if accessToken != nil {
let (saved, keychainError) = self.keychain.saveAccessToken(accessToken!)
if !saved {
result = nil
resultError = keychainError
}
}
self.completionHandler?(result, resultError)
self.completionHandler = nil
}
// MARK: - Helpers
func cleanupCookiesForURL(URL: NSURL) {
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
if storage.cookies != nil {
let cookies = storage.cookies as [NSHTTPCookie]
for cookie in cookies {
if cookie.domain == URL.host {
storage.deleteCookie(cookie as NSHTTPCookie)
}
}
}
}
func extractParametersFromURL(fromURL: NSURL) -> Parameters {
var queryString: String?
let components = NSURLComponents(URL: fromURL, resolvingAgainstBaseURL: false)
if components?.query == nil {
// If we are here it's was web authorization and we have redirect URL like this:
// testapp123://foursquare#access_token=ACCESS_TOKEN
queryString = components?.fragment
} else {
// If we are here it's was native iOS authorization and we have redirect URL like this:
// testapp123://foursquare?access_token=ACCESS_TOKEN
queryString = fromURL.query
}
var parameters = queryString?.componentsSeparatedByString("&")
var map = Parameters()
if parameters != nil {
for string: String in parameters! {
let keyValue = string.componentsSeparatedByString("=")
if keyValue.count == 2 {
map[keyValue[0]] = keyValue[1]
}
}
}
return map
}
func errorForErrorString(errorString: String) -> NSError? {
return nil
}
}
| c700ccc32ee82d491c77c834c0e1ab83 | 35.398438 | 106 | 0.62889 | false | true | false | false |
eRGoon/RGPageViewController | refs/heads/master | RGPageViewController/RGPageViewController/Source/Classes/RGTabBarItem.swift | mit | 1 | //
// RGTabBarItem.swift
// RGPageViewController
//
// Created by Ronny Gerasch on 23.01.17.
// Copyright © 2017 Ronny Gerasch. All rights reserved.
//
import UIKit
// MARK: - RGTabBarItem
open class RGTabBarItem: UIView {
var selected: Bool = false {
didSet {
setSelectedState()
}
}
var text: String?
var image: UIImage?
var textLabel: UILabel?
var imageView: UIImageView?
var normalColor: UIColor? = UIColor.gray
public init(frame: CGRect, text: String?, image: UIImage?, color: UIColor?) {
super.init(frame: frame)
self.text = text
self.image = image?.withRenderingMode(.alwaysTemplate)
if color != nil {
normalColor = color
}
initSelf()
}
public override init(frame: CGRect) {
super.init(frame: frame)
initSelf()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSelf()
}
func initSelf() {
backgroundColor = UIColor.clear
if let img = image {
imageView = UIImageView(image: img)
addSubview(imageView!)
imageView!.tintColor = normalColor
imageView!.center.x = center.x
imageView!.center.y = center.y - 5.0
}
if let txt = text {
textLabel = UILabel()
textLabel!.numberOfLines = 1
textLabel!.text = txt
textLabel!.textAlignment = NSTextAlignment.center
textLabel!.textColor = normalColor
textLabel!.font = UIFont(name: "HelveticaNeue", size: 10)
textLabel!.sizeToFit()
textLabel!.frame = CGRect(x: 0.0, y: frame.size.height - textLabel!.frame.size.height - 3.0, width: frame.size.width, height: textLabel!.frame.size.height)
addSubview(textLabel!)
}
}
func setSelectedState() {
if selected {
textLabel?.textColor = tintColor
imageView?.tintColor = tintColor
} else {
textLabel?.textColor = normalColor
imageView?.tintColor = normalColor
}
}
}
| df87c45edee1cc7540da55d7fcea883f | 21.829545 | 161 | 0.621702 | false | false | false | false |
samodom/TestableUIKit | refs/heads/master | TestableUIKit/UIResponder/UIView/UIViewDecodeRestorableStateSpy.swift | mit | 1 | //
// UIViewDecodeRestorableStateSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 12/10/16.
// Copyright © 2016 Swagger Soft. All rights reserved.
//
import UIKit
import TestSwagger
import FoundationSwagger
public extension UIView {
private static let decodeRestorableStateCalledKeyString = UUIDKeyString()
private static let decodeRestorableStateCalledKey =
ObjectAssociationKey(decodeRestorableStateCalledKeyString)
private static let decodeRestorableStateCalledReference =
SpyEvidenceReference(key: decodeRestorableStateCalledKey)
private static let decodeRestorableStateCoderKeyString = UUIDKeyString()
private static let decodeRestorableStateCoderKey =
ObjectAssociationKey(decodeRestorableStateCoderKeyString)
private static let decodeRestorableStateCoderReference =
SpyEvidenceReference(key: decodeRestorableStateCoderKey)
private static let decodeRestorableStateCoselectors = SpyCoselectors(
methodType: .instance,
original: #selector(UIView.decodeRestorableState(with:)),
spy: #selector(UIView.spy_decodeRestorableState(with:))
)
/// Spy controller for ensuring that a subclass calls its superclass implementation
/// of `decodeRestorableState(with:)` when the same method is invoked on it.
public enum DecodeRestorableStateSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UIView.self
public static let vector = SpyVector.indirect
public static let coselectors: Set = [decodeRestorableStateCoselectors]
public static let evidence: Set = [
decodeRestorableStateCalledReference,
decodeRestorableStateCoderReference
]
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `decodeRestorableState(with:)`
dynamic public func spy_decodeRestorableState(with coder: NSCoder) {
superclassDecodeRestorableStateCalled = true
superclassDecodeRestorableStateCoder = coder
spy_decodeRestorableState(with: coder)
}
/// Indicates whether the `decodeRestorableState(with:)` method has been called on this object's superclass.
public final var superclassDecodeRestorableStateCalled: Bool {
get {
return loadEvidence(with: UIView.decodeRestorableStateCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: UIView.decodeRestorableStateCalledReference)
}
}
/// Provides the captured coder from a call to the `decodeRestorableState(with:)` method, if called.
public final var superclassDecodeRestorableStateCoder: NSCoder? {
get {
return loadEvidence(with: UIView.decodeRestorableStateCoderReference) as? NSCoder
}
set {
let reference = UIView.decodeRestorableStateCoderReference
guard let coder = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(coder, with: reference)
}
}
}
| a2f67af0944f7cb1c758251e68e8de4f | 36 | 112 | 0.722008 | false | false | false | false |
abelsanchezali/ViewBuilder | refs/heads/master | Source/Model/Core/PathFromBundle.swift | mit | 1 | //
// PathFromBundle.swift
// ViewBuilder
//
// Created by Abel Sanchez on 6/25/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import Foundation
open class PathFromBundle: Object, TextDeserializer {
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
guard let value = text else {
return nil
}
// Resolve path:<path> identifier:<identifier>
if let params = service.parseKeyValueSequence(from: value, params: ["path", "identifier"]) {
guard let path = params[0] as? String, let identifier = params[1] as? String else {
return nil
}
return resolvePathFromBundle(resourcePath: path, bundle: Foundation.Bundle(identifier: identifier))
}
// Only one parameter will handled as path
if let chunks = service.parseValueSequence(from: value), chunks.count == 1, let path = chunks[0] as? String {
return resolvePathFromBundle(resourcePath: path)
}
return nil
}
static func resolvePathFromBundle(resourcePath: String, bundle: Foundation.Bundle? = Foundation.Bundle.main) -> String? {
guard let url = URL(string: resourcePath) else {
return nil
}
let normalizedPath = url.path
guard !normalizedPath.isEmpty else {
return nil
}
let targetBundle = bundle ?? Foundation.Bundle.main
let fileName = url.lastPathComponent
guard !fileName.isEmpty else {
return nil
}
let directory = normalizedPath.substring(to: normalizedPath.index(normalizedPath.endIndex, offsetBy: -fileName.count)).trimmingCharacters(in: CharacterSet(charactersIn: "/\\"))
let result = targetBundle.path(forResource: fileName, ofType: nil, inDirectory: directory)
return result
}
}
| 88d14811c7555ab4b29f9ccaca542efe | 36.980392 | 184 | 0.632421 | false | false | false | false |
Fenrikur/ef-app_ios | refs/heads/master | EurofurenceTests/Presenter Tests/Dealer Detail/Presenter Tests/WhenBindingDealerSummaryWithMissingAttributes_DealerDetailPresenterShould.swift | mit | 1 | @testable import Eurofurence
import EurofurenceModel
import XCTest
class WhenBindingDealerSummaryWithMissingAttributes_DealerDetailPresenterShould: XCTestCase {
var context: DealerDetailPresenterTestBuilder.Context!
override func setUp() {
super.setUp()
var summaryViewModel = DealerDetailSummaryViewModel.random
summaryViewModel.artistImagePNGData = nil
summaryViewModel.shortDescription = nil
summaryViewModel.subtitle = nil
summaryViewModel.telegramHandle = nil
summaryViewModel.twitterHandle = nil
summaryViewModel.website = nil
let viewModel = FakeDealerDetailSummaryViewModel(summary: summaryViewModel)
let interactor = FakeDealerDetailInteractor(viewModel: viewModel)
context = DealerDetailPresenterTestBuilder().with(interactor).build()
context.simulateSceneDidLoad()
context.bindComponent(at: 0)
}
func testTellTheArtistArtworkToHideWhenArtworkDataNotAvailable() {
XCTAssertEqual(true, context.boundDealerSummaryComponent?.didHideArtistArtwork)
}
func testTellTheSubtitleToHideWhenNoSubtitleNotAvailable() {
XCTAssertEqual(true, context.boundDealerSummaryComponent?.didHideSubtitle)
}
func testTellTheShortDescriptionToHideWhenNoShortDescriptionNotAvailable() {
XCTAssertEqual(true, context.boundDealerSummaryComponent?.didHideShortDescription)
}
func testTellTheTelegramHandleToHideWhenTelegramHandleNotAvailable() {
XCTAssertEqual(true, context.boundDealerSummaryComponent?.didHideTelegramHandle)
}
func testTellTheTwitterHandleToHideWhenTwitterHandleNotAvailable() {
XCTAssertEqual(true, context.boundDealerSummaryComponent?.didHideTwitterHandle)
}
func testTellTheWebsiteToHideWhenWebsiteNotAvailable() {
XCTAssertEqual(true, context.boundDealerSummaryComponent?.didHideWebsite)
}
}
| 47266308ebdfc90f6cfa2dcc7e9e983c | 37.38 | 93 | 0.775404 | false | true | false | false |
igormatyushkin014/Sensitive | refs/heads/master | Source/Classes/Recognizers/Rotation/RotationGestureRecognizer.swift | mit | 1 | //
// RotationGestureRecognizer.swift
// Sensitive
//
// Created by Igor Matyushkin on 04.01.16.
// Copyright © 2016 Igor Matyushkin. All rights reserved.
//
import UIKit
public class RotationGestureRecognizer: UIRotationGestureRecognizer, UIGestureRecognizerDelegate {
// MARK: Class variables & properties
// MARK: Class methods
// MARK: Initializers
public init(handler: @escaping GestureRecognizerHandler<UIRotationGestureRecognizer>) {
super.init(target: nil, action: nil)
self.handler = handler
self.recognizeSimultaneouslyWithOtherGestures = true
self.addTarget(self, action: #selector(runHandler))
}
// MARK: Deinitializer
deinit {
}
// MARK: Variables & properties
fileprivate var handler: GestureRecognizerHandler<UIRotationGestureRecognizer>?
public var recognizeSimultaneouslyWithOtherGestures: Bool {
get {
return self.delegate === self
}
set {
self.delegate = self
}
}
// MARK: Public methods
// MARK: Private methods
@objc
internal func runHandler() {
self.handler?(self)
}
// MARK: Protocol methods
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| 8b69df8f0ab7a105ada5a0503d7b5796 | 23.3 | 164 | 0.648834 | false | false | false | false |
moltin/ios-swift-example | refs/heads/master | MoltinSwiftExample/MoltinSwiftExample/PaymentViewController.swift | mit | 1 | //
// PaymentViewController.swift
// MoltinSwiftExample
//
// Created by Dylan McKee on 20/08/2015.
// Copyright (c) 2015 Moltin. All rights reserved.
//
import UIKit
import Moltin
class PaymentViewController: UITableViewController, TextEntryTableViewCellDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
// Replace this constant with your store's payment gateway slug
fileprivate let PAYMENT_GATEWAY = "dummy"
fileprivate let PAYMENT_METHOD = "purchase"
// It needs some pass-through variables too...
var emailAddress:String?
var billingDictionary:Dictionary<String, String>?
var shippingDictionary:Dictionary<String, String>?
var selectedShippingMethodSlug:String?
fileprivate var cardNumber:String?
fileprivate var cvvNumber:String?
fileprivate var selectedMonth:String?
fileprivate var selectedYear:String?
fileprivate let CONTINUE_CELL_ROW_INDEX = 3
fileprivate let cardNumberIdentifier = "cardNumber"
fileprivate let cvvNumberIdentifier = "cvvNumber"
fileprivate let datePicker = UIPickerView()
fileprivate var monthsArray = Array<Int>()
fileprivate var yearsArray = Array<String>()
// Validation constants
// Apparently, no credit cards have under 12 or over 19 digits... http://validcreditcardnumbers.info/?p=9
let MAX_CVV_LENGTH = 4
let MIN_CARD_LENGTH = 12
let MAX_CARD_LENGTH = 19
override func viewDidLoad() {
super.viewDidLoad()
datePicker.delegate = self
datePicker.dataSource = self
datePicker.backgroundColor = UIColor.white
datePicker.isOpaque = true
// Populate months
for i in 1...12 {
monthsArray.append(i)
}
// Populate years
let components = (Calendar.current as NSCalendar).components(NSCalendar.Unit.year, from: Date())
let currentYear = components.year
let currentShortYear = (NSString(format: "%d", currentYear!).substring(from: 2) as NSString)
selectedYear = String(format: "%d", currentYear!)
let shortYearNumber = currentShortYear.intValue
let maxYear = shortYearNumber + 5
for i in shortYearNumber...maxYear {
let shortYear = NSString(format: "%d", i)
yearsArray.append(shortYear as String)
}
}
fileprivate func jumpToCartView(_ presentSuccess: Bool) {
for controller in self.navigationController!.viewControllers {
if controller is CartViewController {
self.navigationController!.popToViewController(controller , animated: true)
if presentSuccess {
AlertDialog.showAlert("Order Successful", message: "Your order has been succesful, congratulations", viewController: controller )
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return 4
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath as NSIndexPath).row == CONTINUE_CELL_ROW_INDEX {
let cell = tableView.dequeueReusableCell(withIdentifier: CONTINUE_BUTTON_CELL_IDENTIFIER, for: indexPath) as! ContinueButtonTableViewCell
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: TEXT_ENTRY_CELL_REUSE_IDENTIFIER, for: indexPath) as! TextEntryTableViewCell
// Configure the cell...
switch ((indexPath as NSIndexPath).row) {
case 0:
cell.textField?.placeholder = "Card number"
cell.textField?.keyboardType = UIKeyboardType.numberPad
cell.cellId = cardNumberIdentifier
cell.textField?.text = cardNumber
case 1:
cell.textField?.placeholder = "CVV number"
cell.textField?.keyboardType = UIKeyboardType.numberPad
cell.cellId = cvvNumberIdentifier
cell.textField?.text = cvvNumber
case 2:
cell.textField?.placeholder = "Expiry date"
cell.textField?.inputView = datePicker
cell.textField?.setDoneInputAccessoryView()
cell.cellId = "expiryDate"
if (selectedYear != nil) && (selectedMonth != nil) {
let shortYearNumber = (selectedYear! as NSString).intValue
let shortYear = (NSString(format: "%d", shortYearNumber).substring(from: 2) as NSString)
let formattedDate = String(format: "%@/%@", selectedMonth!, shortYear)
cell.textField?.text = formattedDate
}
cell.hideCursor()
default:
cell.textField?.placeholder = ""
}
cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.delegate = self
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if (indexPath as NSIndexPath).row == CONTINUE_CELL_ROW_INDEX {
// Pay! (after a little validation)
if validateData() {
completeOrder()
}
}
}
//MARK: - Text field Cell Delegate
func textEnteredInCell(_ cell: TextEntryTableViewCell, cellId:String, text: String) {
let cellId = cell.cellId!
if cellId == cardNumberIdentifier {
cardNumber = text
}
if cellId == cvvNumberIdentifier {
cvvNumber = text
}
}
//MARK: - Date picker delegate and data source
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return monthsArray.count
} else {
return yearsArray.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return String(format: "%d", monthsArray[row])
} else {
return yearsArray[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
// Month selected
selectedMonth = String(format: "%d", monthsArray[row])
} else {
// Year selected
// WARNING: The following code won't work past year 2100.
selectedYear = "20" + yearsArray[row]
}
self.tableView.reloadData()
}
// MARK: - Data validation
fileprivate func validateData() -> Bool {
// Check CVV is all numeric, and < max length
if cvvNumber == nil || !cvvNumber!.isNumericString() || (cvvNumber!).characters.count > MAX_CVV_LENGTH {
AlertDialog.showAlert("Invalid CVV Number", message: "Please check the CVV number you entered and try again.", viewController: self)
return false
}
// Check card number is all numeric, and < max length but also > min length
if cardNumber == nil || !cardNumber!.isNumericString() || (cardNumber!).characters.count > MAX_CARD_LENGTH || (cardNumber!).characters.count < MIN_CARD_LENGTH {
AlertDialog.showAlert("Invalid Card Number", message: "Please check the card number you entered and try again.", viewController: self)
return false
}
return true
}
// MARK: - Moltin Order API
fileprivate func completeOrder() {
// Show some loading UI...
SwiftSpinner.show("Completing Purchase")
let firstName = billingDictionary!["first_name"]! as String
let lastName = billingDictionary!["last_name"]! as String
let orderParameters = [
"customer": ["first_name": firstName,
"last_name": lastName,
"email": emailAddress!],
"shipping": self.selectedShippingMethodSlug!,
"gateway": PAYMENT_GATEWAY,
"bill_to": self.billingDictionary!,
"ship_to": self.shippingDictionary!
] as [AnyHashable: Any]
Moltin.sharedInstance().cart.order(withParameters: orderParameters, success: { (response) -> Void in
// Order succesful
print("Order succeeded: \(response)")
// Extract the Order ID so that it can be used in payment too...
let orderId = NSDictionary(dictionary: response!).value(forKeyPath: "result.id") as! String
print("Order ID: \(orderId)")
let paymentParameters = ["data": ["number": self.cardNumber!,
"expiry_month": self.selectedMonth!,
"expiry_year": self.selectedYear!,
"cvv": self.cvvNumber!
]] as [AnyHashable: Any]
Moltin.sharedInstance().checkout.payment(withMethod: self.PAYMENT_METHOD, order: orderId, parameters: paymentParameters, success: { (response) -> Void in
// Payment successful...
print("Payment successful: \(response)")
SwiftSpinner.hide()
self.jumpToCartView(true)
}) { (response, error) -> Void in
// Payment error
print("Payment error: \(error)")
SwiftSpinner.hide()
AlertDialog.showAlert("Payment Failed", message: "Payment failed - please try again", viewController: self)
}
}) { (response, error) -> Void in
// Order failed
print("Order error: \(error)")
SwiftSpinner.hide()
AlertDialog.showAlert("Order Failed", message: "Order failed - please try again", viewController: self)
}
}
}
| 1e7e326b8f1ede99792737c86a423ee2 | 34.144695 | 168 | 0.579414 | false | false | false | false |
maurovc/MyMarvel | refs/heads/master | MyMarvel/WalkthroughUtils.swift | mit | 1 | //
// WalkthroughUtils.swift
// MyMarvel
//
// Created by Mauro Vime Castillo on 27/10/16.
// Copyright © 2016 Mauro Vime Castillo. All rights reserved.
//
import UIKit
import BWWalkthrough
typealias WalkthroughBlock = () -> Void
/// Class that manages all the walkthrough logic.
class WalkthroughUtils: NSObject {
static let walkKey = "walkthrough_v2"
static let sharedUtils = WalkthroughUtils()
var viewController: UIViewController?
var block: WalkthroughBlock?
var walkthrough: CustomWalkthroughViewController?
func showWalkInVC(viewController: UIViewController, block: WalkthroughBlock) {
self.viewController = viewController
self.block = block
viewController.presentViewController(myWalkthrough(), animated: true) {
UIApplication.sharedApplication().statusBarStyle = .Default
}
}
func myWalkthrough() -> CustomWalkthroughViewController {
let storyboard = UIStoryboard(name: "Walkthrough", bundle: nil)
walkthrough = (storyboard.instantiateViewControllerWithIdentifier("walk") as! CustomWalkthroughViewController)
let pageOne = storyboard.instantiateViewControllerWithIdentifier("walk1")
let pageTwo = storyboard.instantiateViewControllerWithIdentifier("walk2")
let pageThr = storyboard.instantiateViewControllerWithIdentifier("walk3")
let pageFou = storyboard.instantiateViewControllerWithIdentifier("walk4")
let pageFiv = storyboard.instantiateViewControllerWithIdentifier("walk5")
let pageSix = storyboard.instantiateViewControllerWithIdentifier("walk6")
walkthrough?.delegate = self
walkthrough?.addViewController(pageOne)
walkthrough?.addViewController(pageTwo)
walkthrough?.addViewController(pageThr)
walkthrough?.addViewController(pageFou)
walkthrough?.addViewController(pageFiv)
walkthrough?.addViewController(pageSix)
walkthrough!.view.sendSubviewToBack(walkthrough!.backgroundView)
return walkthrough!
}
class func needsToShowWalkthrough() -> Bool {
return !NSUserDefaults.standardUserDefaults().boolForKey(walkKey)
}
class func setNeedsToShowWalkthrough(needs: Bool) {
NSUserDefaults.standardUserDefaults().setBool(needs, forKey: walkKey)
}
}
extension WalkthroughUtils: BWWalkthroughViewControllerDelegate {
func walkthroughCloseButtonPressed() {
if (walkthrough!.currentPage + 1) < walkthrough!.numberOfPages {
walkthrough?.nextPage()
} else {
UIApplication.sharedApplication().statusBarStyle = .LightContent
viewController?.dismissViewControllerAnimated(true, completion: nil)
if let _ = block {
block!()
}
}
}
} | 6fdc244d25c3c702ea2cdd6fe08a1be9 | 34.95 | 118 | 0.696348 | false | false | false | false |
cuzv/ExtensionKit | refs/heads/master | Sources/Extension/CALayer+Extension.swift | mit | 1 | //
// CALayer+Extension.swift
// ExtensionKit
//
// Created by Moch Xiao on 2/22/17.
// Copyright © 2017 Moch. All rights reserved.
//
import Foundation
import QuartzCore
// MARK: - Frame & Struct
public extension CALayer {
public var origin: CGPoint {
get { return frame.origin }
set { frame = CGRect(x: newValue.x, y: newValue.y, width: width, height: height) }
}
public var size: CGSize {
get { return frame.size }
set { frame = CGRect(x: minX, y: minY, width: newValue.width, height: newValue.height) }
}
public var minX: CGFloat {
get { return frame.origin.x }
set { frame = CGRect(x: newValue, y: minY, width: width, height: height) }
}
public var left: CGFloat {
get { return frame.origin.x }
set { frame = CGRect(x: newValue, y: minY, width: width, height: height) }
}
public var midX: CGFloat {
get { return frame.midX }
set { frame = CGRect(x: newValue - width * 0.5, y: minY, width: width, height: height) }
}
public var centerX: CGFloat {
get { return frame.midX }
set { frame = CGRect(x: newValue - width * 0.5, y: minY, width: width, height: height) }
}
public var maxX: CGFloat {
get { return minX + width }
set { frame = CGRect(x: newValue - width, y: minY, width: width, height: height) }
}
public var right: CGFloat {
get { return minX + width }
set { frame = CGRect(x: newValue - width, y: minY, width: width, height: height) }
}
public var minY: CGFloat {
get { return frame.origin.y }
set { frame = CGRect(x: minX, y: newValue, width: width, height: height) }
}
public var top: CGFloat {
get { return frame.origin.y }
set { frame = CGRect(x: minX, y: newValue, width: width, height: height) }
}
public var midY: CGFloat {
get { return frame.midY }
set { frame = CGRect(x: minX, y: newValue - height * 0.5, width: width, height: height) }
}
public var centerY: CGFloat {
get { return frame.midY }
set { frame = CGRect(x: minX, y: newValue - height * 0.5, width: width, height: height) }
}
public var maxY: CGFloat {
get { return minY + height }
set { frame = CGRect(x: minX, y: newValue - height, width: width, height: height) }
}
public var bottom: CGFloat {
get { return minY + height }
set { frame = CGRect(x: minX, y: newValue - height, width: width, height: height) }
}
public var width: CGFloat {
get { return bounds.width }
set { frame = CGRect(x: minX, y: minY, width: newValue, height: height) }
}
public var height: CGFloat {
get { return bounds.height }
set { frame = CGRect(x: minX, y: minY, width: width, height: newValue) }
}
public var center: CGPoint {
set { frame = CGRect(x: newValue.x - frame.size.width * 0.5, y: newValue.y - frame.size.height * 0.5, width: width, height: height) }
get { return CGPoint(x: origin.x + size.width * 0.5, y: origin.y + size.height * 0.5) }
}
}
public extension CALayer {
public var snapshotImage: UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public func setShadow(color: UIColor, offset: CGSize, radius: CGFloat) {
shadowColor = color.cgColor
shadowOffset = offset
shadowRadius = radius
shadowOpacity = 1
shouldRasterize = true
rasterizationScale = UIScreen.main.scale
}
public func removeAllSublayers() {
sublayers?.forEach { (sender) in
sender.removeFromSuperlayer()
}
}
}
| 659d57af9fb8abed393ee97f29605f08 | 30.669291 | 141 | 0.586275 | false | false | false | false |
ltcarbonell/deckstravaganza | refs/heads/master | Deckstravaganza/MasterViewController.swift | mit | 1 | //
// MasterViewController.swift
// Deckstravaganza
//
// Created by Stephen on 9/28/15.
// Copyright © 2015 University of Florida. All rights reserved.
//
import UIKit
protocol MenuSelectionDelegate: class {
func menuSelected(_ newMenu: Menu)
}
class MasterViewController: UITableViewController {
var delegate: MenuSelectionDelegate?
var menus: [[Menu]] = [
[Menu(name: "Continue", description: "Continue Playing Last Game")],
[
Menu(name: "New Game", description: "New Game", clickable: false),
Menu(name: "\tSolitaire", description: "New Solitaire Game", level: 2, viewGameOptions: true, gameType: .solitaire),
Menu(name: "\tRummy", description: "New Rummy Game", level: 2, viewGameOptions: true, gameType: .rummy)
]
];
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 numberOfSections(in tableView: UITableView) -> Int {
return menus.count;
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let menuItems = menus[section].count;
if(menus[section].first!.clickable) {
return menuItems;
} else {
return menuItems - 1;
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if(!menus[section].first!.clickable) {
return menus[section].first!.name;
}
return nil;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// Configure the cell...
if(!menus[indexPath.section].first!.clickable) {
let menuItem = self.menus[indexPath.section][indexPath.row + 1];
cell.textLabel?.text = menuItem.name;
return cell;
}
let menuItem = self.menus[indexPath.section][indexPath.row];
cell.textLabel?.text = menuItem.name;
return cell
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedMenu: Menu;
if(self.menus[indexPath.section].first!.clickable) {
selectedMenu = self.menus[indexPath.section][indexPath.row];
} else {
selectedMenu = self.menus[indexPath.section][indexPath.row + 1];
}
if let detailViewController = self.delegate as? DetailViewController {
self.delegate?.menuSelected(selectedMenu);
detailViewController.tearDownMenuUI();
detailViewController.setupMenuUI();
splitViewController?.showDetailViewController(detailViewController, sender: nil)
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false 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 false 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.
}
*/
}
| fabfb7b4e06d30fc4c4afdbce2b220b9 | 33.940397 | 157 | 0.646702 | false | false | false | false |
jzucker2/SwiftyKit | refs/heads/master | Example/Tests/StackingViewTestCase.swift | mit | 1 | //
// StackingViewTestCase.swift
// SwiftyKit_Tests
//
// Created by Jordan Zucker on 8/4/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import XCTest
@testable import SwiftyKit
class StackingViewTestCase: XCTestCase {
struct TestScreen: Screen {
var bounds: CGRect {
return CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0)
}
}
class TestStackedView: UIViewController, StackingView {
let stackView = UIStackView(frame: .zero)
let testScreen: Screen
required init(screen: TestScreen) {
self.testScreen = screen
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
self.view = loadedView(and: self.testScreen)
}
}
class TestNonDefaultOptionsStackedView: UIViewController, StackingView {
let stackView = UIStackView(frame: .zero)
let testScreen: Screen
required init(screen: TestScreen) {
self.testScreen = screen
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
self.view = loadedView(and: self.testScreen)
}
static var stackViewOptions: StackViewOptions {
return StackViewOptions(axis: .horizontal, alignment: .center, distribution: .equalCentering, backgroundColor: .red)
}
}
let testScreen = TestScreen()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testStackViewExistsWithLoadViewConvenience() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let testStackedView = TestStackedView(screen: self.testScreen)
XCTAssertNotNil(testStackedView)
testStackedView.loadViewIfNeeded()
testStackedView.view.layoutIfNeeded()
print(testStackedView.view.frame)
print(testStackedView.stackView.frame)
XCTAssertNotNil(testStackedView.stackView)
XCTAssertEqual(testScreen.bounds, testStackedView.view.frame)
XCTAssertEqual(testScreen.bounds, testStackedView.stackView.frame)
XCTAssertEqual(testStackedView.view, testStackedView.stackView.superview!)
}
func testDefaultOptions() {
let defaultOptions = StackViewOptions.defaultOptions()
XCTAssertEqual(defaultOptions.axis, .vertical)
XCTAssertEqual(defaultOptions.alignment, .fill)
XCTAssertEqual(defaultOptions.distribution, .fill)
XCTAssertEqual(defaultOptions.backgroundColor, .white)
}
func testStackingAppliesDefaultOptions() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let testStackedView = TestStackedView(screen: self.testScreen)
XCTAssertNotNil(testStackedView)
testStackedView.loadViewIfNeeded()
testStackedView.view.layoutIfNeeded()
XCTAssertNotNil(testStackedView.stackView)
let defaultOptions = StackViewOptions.defaultOptions()
XCTAssertEqual(testStackedView.stackView.axis, defaultOptions.axis)
XCTAssertEqual(testStackedView.stackView.distribution, defaultOptions.distribution)
XCTAssertEqual(testStackedView.stackView.alignment, defaultOptions.alignment)
XCTAssertEqual(testStackedView.view.backgroundColor, defaultOptions.backgroundColor)
}
func testAppliesSubclassOverrideStackViewOptions() {
let testStackedView = TestNonDefaultOptionsStackedView(screen: self.testScreen)
XCTAssertNotNil(testStackedView)
testStackedView.loadViewIfNeeded()
testStackedView.view.layoutIfNeeded()
let stackView = testStackedView.stackView
XCTAssertNotNil(stackView)
let differentOptions = TestNonDefaultOptionsStackedView.stackViewOptions
XCTAssertEqual(stackView.axis, .horizontal)
XCTAssertEqual(stackView.axis, differentOptions.axis)
XCTAssertEqual(stackView.distribution, .equalCentering)
XCTAssertEqual(stackView.distribution, differentOptions.distribution)
XCTAssertEqual(stackView.alignment, .center)
XCTAssertEqual(stackView.alignment, differentOptions.alignment)
XCTAssertEqual(testStackedView.view.backgroundColor, .red)
XCTAssertEqual(testStackedView.view.backgroundColor, differentOptions.backgroundColor)
}
}
| 920ea6b7db4334011bc789f138e2e8e0 | 37.871212 | 128 | 0.680374 | false | true | false | false |
TakeScoop/SwiftyRSA | refs/heads/master | Source/EncryptedMessage.swift | mit | 1 | //
// EncryptedMessage.swift
// SwiftyRSA
//
// Created by Lois Di Qual on 5/18/17.
// Copyright © 2017 Scoop. All rights reserved.
//
import Foundation
public class EncryptedMessage: Message {
/// Data of the message
public let data: Data
/// Creates an encrypted message with data.
///
/// - Parameter data: Data of the encrypted message.
public required init(data: Data) {
self.data = data
}
/// Decrypts an encrypted message with a private key and returns a clear message.
///
/// - Parameters:
/// - key: Private key to decrypt the mssage with
/// - padding: Padding to use during the decryption
/// - Returns: Clear message
/// - Throws: SwiftyRSAError
public func decrypted(with key: PrivateKey, padding: Padding) throws -> ClearMessage {
let blockSize = SecKeyGetBlockSize(key.reference)
var encryptedDataAsArray = [UInt8](repeating: 0, count: data.count)
(data as NSData).getBytes(&encryptedDataAsArray, length: data.count)
var decryptedDataBytes = [UInt8](repeating: 0, count: 0)
var idx = 0
while idx < encryptedDataAsArray.count {
let idxEnd = min(idx + blockSize, encryptedDataAsArray.count)
let chunkData = [UInt8](encryptedDataAsArray[idx..<idxEnd])
var decryptedDataBuffer = [UInt8](repeating: 0, count: blockSize)
var decryptedDataLength = blockSize
let status = SecKeyDecrypt(key.reference, padding, chunkData, idxEnd-idx, &decryptedDataBuffer, &decryptedDataLength)
guard status == noErr else {
throw SwiftyRSAError.chunkDecryptFailed(index: idx)
}
decryptedDataBytes += [UInt8](decryptedDataBuffer[0..<decryptedDataLength])
idx += blockSize
}
let decryptedData = Data(bytes: decryptedDataBytes, count: decryptedDataBytes.count)
return ClearMessage(data: decryptedData)
}
}
| c868fb532d8a6a824804e3a7a9fd4367 | 34.220339 | 129 | 0.619346 | false | false | false | false |
ben-ng/swift | refs/heads/master | test/expr/cast/as_coerce.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift
// Test the use of 'as' for type coercion (which requires no checking).
@objc protocol P1 {
func foo()
}
class A : P1 {
@objc func foo() { }
}
@objc class B : A {
func bar() { }
}
func doFoo() {}
func test_coercion(_ a: A, b: B) {
// Coercion to a protocol type
let x = a as P1
x.foo()
// Coercion to a superclass type
let y = b as A
y.foo()
}
class C : B { }
class D : C { }
func prefer_coercion(_ c: inout C) {
let d = c as! D
c = d
}
// Coerce literals
var i32 = 1 as Int32
var i8 = -1 as Int8
// Coerce to a superclass with generic parameter inference
class C1<T> {
func f(_ x: T) { }
}
class C2<T> : C1<Int> { }
var c2 = C2<()>()
var c1 = c2 as C1
c1.f(5)
@objc protocol P {}
class CC : P {}
let cc: Any = CC()
if cc is P {
doFoo()
}
if let p = cc as? P {
doFoo()
}
// Test that 'as?' coercion fails.
let strImplicitOpt: String! = nil
_ = strImplicitOpt as? String // expected-warning{{conditional cast from 'String!' to 'String' always succeeds}}
class C3 {}
class C4 : C3 {}
class C5 {}
var c: AnyObject = C3()
if let castX = c as! C4? {} // expected-error {{cannot downcast from 'AnyObject' to a more optional type 'C4?'}}
// Only suggest replacing 'as' with 'as!' if it would fix the error.
C3() as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{6-8=as!}}
C3() as C5 // expected-error {{cannot convert value of type 'C3' to type 'C5' in coercion}}
// Diagnostic shouldn't include @lvalue in type of c3.
var c3 = C3()
c3 as C4 // expected-error {{'C3' is not convertible to 'C4'; did you mean to use 'as!' to force downcast?}} {{4-6=as!}}
// <rdar://problem/19495142> Various incorrect diagnostics for explicit type conversions
1 as Double as Float // expected-error{{cannot convert value of type 'Double' to type 'Float' in coercion}}
1 as Int as String // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}}
Double(1) as Double as String // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}}
["awd"] as [Int] // expected-error{{cannot convert value of type 'String' to expected element type 'Int'}}
([1, 2, 1.0], 1) as ([String], Int) // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}}
[[1]] as [[String]] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}}
(1, 1.0) as (Int, Int) // expected-error{{cannot convert value of type 'Double' to type 'Int' in coercion}}
(1.0, 1, "asd") as (String, Int, Float) // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}}
(1, 1.0, "a", [1, 23]) as (Int, Double, String, [String]) // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}}
[1] as! [String] // expected-error{{'[Int]' is not convertible to '[String]'}}
[(1, (1, 1))] as! [(Int, (String, Int))] // expected-error{{'[(Int, (Int, Int))]' is not convertible to '[(Int, (String, Int))]'}}
// <rdar://problem/19495253> Incorrect diagnostic for explicitly casting to the same type
_ = "hello" as! String // expected-warning{{forced cast of 'String' to same type has no effect}} {{13-24=}}
// <rdar://problem/19499340> QoI: Nimble as -> as! changes not covered by Fix-Its
func f(_ x : String) {}
f("what" as Any as String) // expected-error {{'Any' is not convertible to 'String'; did you mean to use 'as!' to force downcast?}} {{17-19=as!}}
f(1 as String) // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}}
// <rdar://problem/19650402> Swift compiler segfaults while running the annotation tests
let s : AnyObject = C3()
s as C3 // expected-error{{'AnyObject' is not convertible to 'C3'; did you mean to use 'as!' to force downcast?}} {{3-5=as!}}
| 58aeffdf4d5db91006a3e2b084f97261 | 35.961538 | 147 | 0.655567 | false | false | false | false |
dobleuber/my-swift-exercises | refs/heads/master | Project22/Project22/ViewController.swift | mit | 1 | //
// ViewController.swift
// Project22
//
// Created by Wbert Castro on 2/08/17.
// Copyright © 2017 Wbert Castro. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var distanceReading: UILabel!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
view.backgroundColor = UIColor.gray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways {
if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
if CLLocationManager.isRangingAvailable() {
startScanning()
}
}
}
}
func startScanning() {
let uuid = UUID(uuidString: "D9B9EC1F-3925-43D0-80A9-1E39D4CEA95C")!
let beaconRegion = CLBeaconRegion(proximityUUID: uuid, major: 123, identifier: "MyBeacon")
locationManager.startMonitoring(for: beaconRegion)
locationManager.startRangingBeacons(in: beaconRegion)
}
func update(distance: CLProximity) {
UIView.animate(withDuration: 0.8) {
[unowned self] in
switch distance {
case .unknown:
self.view.backgroundColor = UIColor.gray
self.distanceReading.text = "UNKNOWN"
case .far:
self.view.backgroundColor = UIColor.blue
self.distanceReading.text = "FAR"
case .near:
self.view.backgroundColor = UIColor.orange
self.distanceReading.text = "NEAR"
case .immediate:
self.view.backgroundColor = UIColor.red
self.distanceReading.text = "RIGHT HERE"
}
}
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
if beacons.count > 0 {
let beacon = beacons[0]
update(distance: beacon.proximity)
} else {
update(distance: .unknown)
}
}
}
| 22a968fe64f75a12d04bbaaf425ee086 | 30.378049 | 120 | 0.600466 | false | false | false | false |
zvonicek/ImageSlideshow | refs/heads/master | ImageSlideshow/Classes/Core/ZoomAnimatedTransitioning.swift | mit | 1 | //
// ZoomAnimatedTransitioning.swift
// ImageSlideshow
//
// Created by Petr Zvoníček on 31.08.15.
//
//
import UIKit
@objcMembers
open class ZoomAnimatedTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
/// parent image view used for animated transition
open var referenceImageView: UIImageView?
/// parent slideshow view used for animated transition
open weak var referenceSlideshowView: ImageSlideshow?
// must be weak because FullScreenSlideshowViewController has strong reference to its transitioning delegate
weak var referenceSlideshowController: FullScreenSlideshowViewController?
var referenceSlideshowViewFrame: CGRect?
var gestureRecognizer: UIPanGestureRecognizer!
fileprivate var interactionController: UIPercentDrivenInteractiveTransition?
/// Enables or disables swipe-to-dismiss interactive transition
open var slideToDismissEnabled: Bool = true
/**
Init the transitioning delegate with a source ImageSlideshow
- parameter slideshowView: ImageSlideshow instance to animate the transition from
- parameter slideshowController: FullScreenViewController instance to animate the transition to
*/
public init(slideshowView: ImageSlideshow, slideshowController: FullScreenSlideshowViewController) {
self.referenceSlideshowView = slideshowView
self.referenceSlideshowController = slideshowController
super.init()
initialize()
}
/**
Init the transitioning delegate with a source ImageView
- parameter imageView: UIImageView instance to animate the transition from
- parameter slideshowController: FullScreenViewController instance to animate the transition to
*/
public init(imageView: UIImageView, slideshowController: FullScreenSlideshowViewController) {
self.referenceImageView = imageView
self.referenceSlideshowController = slideshowController
super.init()
initialize()
}
func initialize() {
// Pan gesture recognizer for interactive dismiss
gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ZoomAnimatedTransitioningDelegate.handleSwipe(_:)))
gestureRecognizer.delegate = self
// Append it to a window otherwise it will be canceled during the transition
UIApplication.shared.keyWindow?.addGestureRecognizer(gestureRecognizer)
}
func handleSwipe(_ gesture: UIPanGestureRecognizer) {
guard let referenceSlideshowController = referenceSlideshowController else {
return
}
let percent = min(max(abs(gesture.translation(in: gesture.view!).y) / 200.0, 0.0), 1.0)
if gesture.state == .began {
interactionController = UIPercentDrivenInteractiveTransition()
referenceSlideshowController.dismiss(animated: true, completion: nil)
} else if gesture.state == .changed {
interactionController?.update(percent)
} else if gesture.state == .ended || gesture.state == .cancelled || gesture.state == .failed {
let velocity = gesture.velocity(in: referenceSlideshowView)
if abs(velocity.y) > 500 {
if let pageSelected = referenceSlideshowController.pageSelected {
pageSelected(referenceSlideshowController.slideshow.currentPage)
}
interactionController?.finish()
} else if percent > 0.5 {
if let pageSelected = referenceSlideshowController.pageSelected {
pageSelected(referenceSlideshowController.slideshow.currentPage)
}
interactionController?.finish()
} else {
interactionController?.cancel()
}
interactionController = nil
}
}
open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if let reference = referenceSlideshowView {
return ZoomInAnimator(referenceSlideshowView: reference, parent: self)
} else if let reference = referenceImageView {
return ZoomInAnimator(referenceImageView: reference, parent: self)
} else {
return nil
}
}
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if let reference = referenceSlideshowView {
return ZoomOutAnimator(referenceSlideshowView: reference, parent: self)
} else if let reference = referenceImageView {
return ZoomOutAnimator(referenceImageView: reference, parent: self)
} else {
return nil
}
}
open func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactionController
}
open func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactionController
}
public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return PresentationController(presentedViewController: presented, presenting: presenting)
}
}
private class PresentationController: UIPresentationController {
// Needed for interactive dismiss to keep the presenter View Controller visible
override var shouldRemovePresentersView: Bool {
return false
}
}
extension ZoomAnimatedTransitioningDelegate: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer else {
return false
}
if !slideToDismissEnabled {
return false
}
if let currentItem = referenceSlideshowController?.slideshow.currentSlideshowItem, currentItem.isZoomed() {
return false
}
if let view = gestureRecognizer.view {
let velocity = gestureRecognizer.velocity(in: view)
return abs(velocity.x) < abs(velocity.y)
}
return true
}
}
@objcMembers
class ZoomAnimator: NSObject {
var referenceImageView: UIImageView?
var referenceSlideshowView: ImageSlideshow?
var parent: ZoomAnimatedTransitioningDelegate
init(referenceSlideshowView: ImageSlideshow, parent: ZoomAnimatedTransitioningDelegate) {
self.referenceSlideshowView = referenceSlideshowView
self.referenceImageView = referenceSlideshowView.currentSlideshowItem?.imageView
self.parent = parent
super.init()
}
init(referenceImageView: UIImageView, parent: ZoomAnimatedTransitioningDelegate) {
self.referenceImageView = referenceImageView
self.parent = parent
super.init()
}
}
@objcMembers
class ZoomInAnimator: ZoomAnimator, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// Pauses slideshow
self.referenceSlideshowView?.pauseTimer()
let containerView = transitionContext.containerView
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
guard let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? FullScreenSlideshowViewController else {
return
}
toViewController.view.frame = transitionContext.finalFrame(for: toViewController)
let transitionBackgroundView = UIView(frame: containerView.frame)
transitionBackgroundView.backgroundColor = toViewController.backgroundColor
containerView.addSubview(transitionBackgroundView)
#if swift(>=4.2)
containerView.sendSubviewToBack(transitionBackgroundView)
#else
containerView.sendSubview(toBack: transitionBackgroundView)
#endif
let finalFrame = toViewController.view.frame
var transitionView: UIImageView?
var transitionViewFinalFrame = finalFrame
if let referenceImageView = referenceImageView {
transitionView = UIImageView(image: referenceImageView.image)
transitionView!.contentMode = UIViewContentMode.scaleAspectFill
transitionView!.clipsToBounds = true
transitionView!.frame = containerView.convert(referenceImageView.bounds, from: referenceImageView)
containerView.addSubview(transitionView!)
self.parent.referenceSlideshowViewFrame = transitionView!.frame
referenceImageView.alpha = 0
if let image = referenceImageView.image {
transitionViewFinalFrame = image.tgr_aspectFitRectForSize(finalFrame.size)
}
}
if let item = toViewController.slideshow.currentSlideshowItem, item.zoomInInitially {
transitionViewFinalFrame.size = CGSize(width: transitionViewFinalFrame.size.width * item.maximumZoomScale, height: transitionViewFinalFrame.size.height * item.maximumZoomScale)
}
let duration: TimeInterval = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: UIViewAnimationOptions.curveLinear, animations: {
fromViewController.view.alpha = 0
transitionView?.frame = transitionViewFinalFrame
transitionView?.center = CGPoint(x: finalFrame.midX, y: finalFrame.midY)
}, completion: {[ref = self.referenceImageView] _ in
fromViewController.view.alpha = 1
ref?.alpha = 1
transitionView?.removeFromSuperview()
transitionBackgroundView.removeFromSuperview()
containerView.addSubview(toViewController.view)
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
class ZoomOutAnimator: ZoomAnimator, UIViewControllerAnimatedTransitioning {
private var animatorForCurrentTransition: UIViewImplicitlyAnimating?
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.25
}
@available(iOS 10.0, *)
func interruptibleAnimator(using transitionContext: UIViewControllerContextTransitioning) -> UIViewImplicitlyAnimating {
// as per documentation, the same object should be returned for the ongoing transition
if let animatorForCurrentSession = animatorForCurrentTransition {
return animatorForCurrentSession
}
let params = animationParams(using: transitionContext)
let animator = UIViewPropertyAnimator(duration: params.0, curve: .linear, animations: params.1)
animator.addCompletion(params.2)
animatorForCurrentTransition = animator
return animator
}
private func animationParams(using transitionContext: UIViewControllerContextTransitioning) -> (TimeInterval, () -> Void, (Any) -> Void) {
let toViewController: UIViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
guard let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? FullScreenSlideshowViewController else {
fatalError("Transition not used with FullScreenSlideshowViewController")
}
let containerView = transitionContext.containerView
var transitionViewInitialFrame: CGRect
if let currentSlideshowItem = fromViewController.slideshow.currentSlideshowItem {
if let image = currentSlideshowItem.imageView.image {
transitionViewInitialFrame = image.tgr_aspectFitRectForSize(currentSlideshowItem.imageView.frame.size)
} else {
transitionViewInitialFrame = currentSlideshowItem.imageView.frame
}
transitionViewInitialFrame = containerView.convert(transitionViewInitialFrame, from: currentSlideshowItem)
} else {
transitionViewInitialFrame = fromViewController.slideshow.frame
}
var transitionViewFinalFrame: CGRect
if let referenceImageView = referenceImageView {
referenceImageView.alpha = 0
let referenceSlideshowViewFrame = containerView.convert(referenceImageView.bounds, from: referenceImageView)
transitionViewFinalFrame = referenceSlideshowViewFrame
// do a frame scaling when AspectFit content mode enabled
if fromViewController.slideshow.currentSlideshowItem?.imageView.image != nil && referenceImageView.contentMode == UIViewContentMode.scaleAspectFit {
transitionViewFinalFrame = containerView.convert(referenceImageView.aspectToFitFrame(), from: referenceImageView)
}
// fixes the problem when the referenceSlideshowViewFrame was shifted during change of the status bar hidden state
if UIApplication.shared.isStatusBarHidden && !toViewController.prefersStatusBarHidden && referenceSlideshowViewFrame.origin.y != parent.referenceSlideshowViewFrame?.origin.y {
transitionViewFinalFrame = transitionViewFinalFrame.offsetBy(dx: 0, dy: 20)
}
} else {
transitionViewFinalFrame = referenceSlideshowView?.frame ?? CGRect.zero
}
let transitionBackgroundView = UIView(frame: containerView.frame)
transitionBackgroundView.backgroundColor = fromViewController.backgroundColor
containerView.addSubview(transitionBackgroundView)
#if swift(>=4.2)
containerView.sendSubviewToBack(transitionBackgroundView)
#else
containerView.sendSubview(toBack: transitionBackgroundView)
#endif
let transitionView = UIImageView(image: fromViewController.slideshow.currentSlideshowItem?.imageView.image)
transitionView.contentMode = UIViewContentMode.scaleAspectFill
transitionView.clipsToBounds = true
transitionView.frame = transitionViewInitialFrame
containerView.addSubview(transitionView)
fromViewController.view.isHidden = true
let duration = transitionDuration(using: transitionContext)
let animations = {
transitionBackgroundView.alpha = 0
transitionView.frame = transitionViewFinalFrame
}
let completion = { (_: Any) in
let completed = !transitionContext.transitionWasCancelled
self.referenceImageView?.alpha = 1
if completed {
fromViewController.view.removeFromSuperview()
UIApplication.shared.keyWindow?.removeGestureRecognizer(self.parent.gestureRecognizer)
// Unpauses slideshow
self.referenceSlideshowView?.unpauseTimer()
} else {
fromViewController.view.isHidden = false
}
transitionView.removeFromSuperview()
transitionBackgroundView.removeFromSuperview()
self.animatorForCurrentTransition = nil
transitionContext.completeTransition(completed)
}
return (duration, animations, completion)
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// Working around iOS 10+ breaking change requiring to use UIPropertyAnimator for proper interactive transition instead of UIView.animate
if #available(iOS 10.0, *) {
interruptibleAnimator(using: transitionContext).startAnimation()
} else {
let params = animationParams(using: transitionContext)
UIView.animate(withDuration: params.0, delay: 0, options: UIViewAnimationOptions(), animations: params.1, completion: params.2)
}
}
}
| a4b83991a075fb1cca382307353e8c8a | 42.80914 | 188 | 0.71461 | false | false | false | false |
httpswift/swifter | refs/heads/stable | Xcode/Sources/Socket.swift | bsd-3-clause | 1 | //
// Socket.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public enum SocketError: Error {
case socketCreationFailed(String)
case socketSettingReUseAddrFailed(String)
case bindFailed(String)
case listenFailed(String)
case writeFailed(String)
case getPeerNameFailed(String)
case convertingPeerNameFailed
case getNameInfoFailed(String)
case acceptFailed(String)
case recvFailed(String)
case getSockNameFailed(String)
}
// swiftlint: disable identifier_name
open class Socket: Hashable, Equatable {
let socketFileDescriptor: Int32
private var shutdown = false
public init(socketFileDescriptor: Int32) {
self.socketFileDescriptor = socketFileDescriptor
}
deinit {
close()
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.socketFileDescriptor)
}
public func close() {
if shutdown {
return
}
shutdown = true
Socket.close(self.socketFileDescriptor)
}
public func port() throws -> in_port_t {
var addr = sockaddr_in()
return try withUnsafePointer(to: &addr) { pointer in
var len = socklen_t(MemoryLayout<sockaddr_in>.size)
if getsockname(socketFileDescriptor, UnsafeMutablePointer(OpaquePointer(pointer)), &len) != 0 {
throw SocketError.getSockNameFailed(Errno.description())
}
let sin_port = pointer.pointee.sin_port
#if os(Linux)
return ntohs(sin_port)
#else
return Int(OSHostByteOrder()) != OSLittleEndian ? sin_port.littleEndian : sin_port.bigEndian
#endif
}
}
public func isIPv4() throws -> Bool {
var addr = sockaddr_in()
return try withUnsafePointer(to: &addr) { pointer in
var len = socklen_t(MemoryLayout<sockaddr_in>.size)
if getsockname(socketFileDescriptor, UnsafeMutablePointer(OpaquePointer(pointer)), &len) != 0 {
throw SocketError.getSockNameFailed(Errno.description())
}
return Int32(pointer.pointee.sin_family) == AF_INET
}
}
public func writeUTF8(_ string: String) throws {
try writeUInt8(ArraySlice(string.utf8))
}
public func writeUInt8(_ data: [UInt8]) throws {
try writeUInt8(ArraySlice(data))
}
public func writeUInt8(_ data: ArraySlice<UInt8>) throws {
try data.withUnsafeBufferPointer {
try writeBuffer($0.baseAddress!, length: data.count)
}
}
public func writeData(_ data: NSData) throws {
try writeBuffer(data.bytes, length: data.length)
}
public func writeData(_ data: Data) throws {
#if compiler(>=5.0)
try data.withUnsafeBytes { (body: UnsafeRawBufferPointer) -> Void in
if let baseAddress = body.baseAddress, body.count > 0 {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
try self.writeBuffer(pointer, length: data.count)
}
}
#else
try data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) -> Void in
try self.writeBuffer(pointer, length: data.count)
}
#endif
}
private func writeBuffer(_ pointer: UnsafeRawPointer, length: Int) throws {
var sent = 0
while sent < length {
#if os(Linux)
let result = send(self.socketFileDescriptor, pointer + sent, Int(length - sent), Int32(MSG_NOSIGNAL))
#else
let result = write(self.socketFileDescriptor, pointer + sent, Int(length - sent))
#endif
if result <= 0 {
throw SocketError.writeFailed(Errno.description())
}
sent += result
}
}
/// Read a single byte off the socket. This method is optimized for reading
/// a single byte. For reading multiple bytes, use read(length:), which will
/// pre-allocate heap space and read directly into it.
///
/// - Returns: A single byte
/// - Throws: SocketError.recvFailed if unable to read from the socket
open func read() throws -> UInt8 {
var byte: UInt8 = 0
#if os(Linux)
let count = Glibc.read(self.socketFileDescriptor as Int32, &byte, 1)
#else
let count = Darwin.read(self.socketFileDescriptor as Int32, &byte, 1)
#endif
guard count > 0 else {
throw SocketError.recvFailed(Errno.description())
}
return byte
}
/// Read up to `length` bytes from this socket
///
/// - Parameter length: The maximum bytes to read
/// - Returns: A buffer containing the bytes read
/// - Throws: SocketError.recvFailed if unable to read bytes from the socket
open func read(length: Int) throws -> [UInt8] {
return try [UInt8](unsafeUninitializedCapacity: length) { buffer, bytesRead in
bytesRead = try read(into: &buffer, length: length)
}
}
static let kBufferLength = 1024
/// Read up to `length` bytes from this socket into an existing buffer
///
/// - Parameter into: The buffer to read into (must be at least length bytes in size)
/// - Parameter length: The maximum bytes to read
/// - Returns: The number of bytes read
/// - Throws: SocketError.recvFailed if unable to read bytes from the socket
func read(into buffer: inout UnsafeMutableBufferPointer<UInt8>, length: Int) throws -> Int {
var offset = 0
guard let baseAddress = buffer.baseAddress else { return 0 }
while offset < length {
// Compute next read length in bytes. The bytes read is never more than kBufferLength at once.
let readLength = offset + Socket.kBufferLength < length ? Socket.kBufferLength : length - offset
#if os(Linux)
let bytesRead = Glibc.read(self.socketFileDescriptor as Int32, baseAddress + offset, readLength)
#else
let bytesRead = Darwin.read(self.socketFileDescriptor as Int32, baseAddress + offset, readLength)
#endif
guard bytesRead > 0 else {
throw SocketError.recvFailed(Errno.description())
}
offset += bytesRead
}
return offset
}
private static let CR: UInt8 = 13
private static let NL: UInt8 = 10
public func readLine() throws -> String {
var characters: String = ""
var index: UInt8 = 0
repeat {
index = try self.read()
if index > Socket.CR { characters.append(Character(UnicodeScalar(index))) }
} while index != Socket.NL
return characters
}
public func peername() throws -> String {
var addr = sockaddr(), len: socklen_t = socklen_t(MemoryLayout<sockaddr>.size)
if getpeername(self.socketFileDescriptor, &addr, &len) != 0 {
throw SocketError.getPeerNameFailed(Errno.description())
}
var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if getnameinfo(&addr, len, &hostBuffer, socklen_t(hostBuffer.count), nil, 0, NI_NUMERICHOST) != 0 {
throw SocketError.getNameInfoFailed(Errno.description())
}
return String(cString: hostBuffer)
}
public class func setNoSigPipe(_ socket: Int32) {
#if os(Linux)
// There is no SO_NOSIGPIPE in Linux (nor some other systems). You can instead use the MSG_NOSIGNAL flag when calling send(),
// or use signal(SIGPIPE, SIG_IGN) to make your entire application ignore SIGPIPE.
#else
// Prevents crashes when blocking calls are pending and the app is paused ( via Home button ).
var no_sig_pipe: Int32 = 1
setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &no_sig_pipe, socklen_t(MemoryLayout<Int32>.size))
#endif
}
public class func close(_ socket: Int32) {
#if os(Linux)
_ = Glibc.close(socket)
#else
_ = Darwin.close(socket)
#endif
}
}
public func == (socket1: Socket, socket2: Socket) -> Bool {
return socket1.socketFileDescriptor == socket2.socketFileDescriptor
}
| 83bce8b939f2e51ed6badc8b2b07aea1 | 34.114407 | 137 | 0.618318 | false | false | false | false |
exercism/xswift | refs/heads/master | exercises/luhn/Sources/Luhn/LuhnExample.swift | mit | 2 | import Foundation
struct Luhn {
var number: Int64 = 0
var numberString: String = ""
var addends: [Int] { return addendsFunc(numberString) }
var checksum: Int { return addends.reduce(0, +) }
var isValid: Bool = false
init(_ num: String ) {
self.numberString = num.replacingOccurrences(of: " ", with: "")
let num = Int64(numberString)
if self.numberString.utf16.count <= 1 {
self.isValid = false
} else if num == nil {
isValid = false
} else {
self.number = num!
isValid = checksum % 10 == 0
}
}
func addendsFunc(_ num: String) -> [Int] {
func oddIndexInt64Minus9( _ input: [Int]) -> [Int] {
var input = input
input = Array(input.reversed())
var tempArray: [Int] = []
for (inx, each) in input.enumerated() {
var tempEach: Int = each
if (inx+1) % 2 == 0 {
tempEach *= 2
if tempEach >= 10 {
tempEach -= 9
}
tempArray.insert(tempEach, at: 0)
} else {
tempArray.insert(tempEach, at: 0)
}
}
return tempArray
}
func char2Int(_ input: Character) -> Int {
let tempInt = Int(String(input)) ?? -1 // -1 = error
return tempInt
}
return oddIndexInt64Minus9(Array(num).map { char2Int($0) })
}
}
| 708f96e29c77ae0273b04390d7d45c46 | 29.235294 | 71 | 0.470817 | false | false | false | false |
r-mckay/montreal-iqa | refs/heads/master | montrealIqa/Carthage/Checkouts/Reusable/Example/ReusableDemo iOS/TableViewController.swift | mit | 1 | //
// ViewController.swift
// ReusableDemo
//
// Created by Olivier Halligon on 19/01/2016.
// Copyright © 2016 AliSoftware. All rights reserved.
//
import UIKit
final class TableViewController: UITableViewController {
var boolValues = [false, false]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(cellType: MySimpleColorCell.self)
tableView.register(cellType: MyXIBTextCell.self)
tableView.register(cellType: MyXIBInfoCell.self)
/* No need to register this one, the UIStoryboard already auto-register its cells */
// tableView.registerReusableCell(MyStoryBoardIndexPathCell)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return MyHeaderTableView.height
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let frame = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: self.tableView(tableView, heightForHeaderInSection: section))
// See the overridden `MyHeaderTableView.init(frame:)` initializer, which
// automatically loads the view content from its nib using loadNibContent()
let view = MyHeaderTableView(frame: frame)
view.fillForSection(section)
return view
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 4
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let colorCell = tableView.dequeueReusableCell(for: indexPath) as MySimpleColorCell
let red: CGFloat = indexPath.row == 0 ? 1.0 : 0.0
colorCell.fill(UIColor(red: red, green: 0.0, blue: 1-red, alpha: 1.0))
return colorCell
case 1:
let textCell = tableView.dequeueReusableCell(for: indexPath) as MyXIBTextCell
textCell.fill("{section \(indexPath.section), row \(indexPath.row)}")
return textCell
case 2:
let infoCell = tableView.dequeueReusableCell(for: indexPath) as MyXIBInfoCell
infoCell.fill("InfoCell #\(indexPath.row)", info: "Info #\(indexPath.row)", details: "Details #\(indexPath.row)")
return infoCell
case 3:
let pathCell = tableView.dequeueReusableCell(for: indexPath) as MyStoryBoardIndexPathCell
pathCell.fill(indexPath)
return pathCell
default:
fatalError("Out of bounds, should not happen")
}
}
}
| e72e085d525b0f9231e2b7a9e81ca304 | 35.514286 | 140 | 0.719875 | false | false | false | false |
galacemiguel/bluehacks2017 | refs/heads/master | Project Civ-1/Project Civ/ProjectViewController.swift | mit | 1 | //
// ProjectViewController.swift
// Project Civ
//
// Created by Carlos Arcenas on 2/18/17.
// Copyright © 2017 Rogue Three. All rights reserved.
//
import UIKit
import IGListKit
class ProjectViewController: UIViewController {
var interactor: Interactor? = nil
var projectSelected: Project?
let collectionView: IGListCollectionView = {
let view = IGListCollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout())
view.backgroundColor = UIColor.white
return view
}()
lazy var adapter: IGListAdapter = {
return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0)
}()
// var updates = [ProjectUpdate]()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
adapter.collectionView = collectionView
adapter.dataSource = self
ProjectSource.sharedInstance.fetchUpdatesForProject(projectSelected!) { (updates) in
self.projectSelected!.updates = updates!
self.adapter.reloadData(completion: nil)
}
view.backgroundColor = UIColor(hex6: 0xEEEEEE)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
@IBAction func handleGesture(_ sender: UIPanGestureRecognizer) {
let percentThreshold:CGFloat = 0.3
// convert y-position to downward pull progress (percentage)
let translation = sender.translation(in: view)
let verticalMovement = translation.y / view.bounds.height
let downwardMovement = fmaxf(Float(verticalMovement), 0.0)
let downwardMovementPercent = fminf(downwardMovement, 1.0)
let progress = CGFloat(downwardMovementPercent)
guard let interactor = interactor else { return }
switch sender.state {
case .began:
interactor.hasStarted = true
dismiss(animated: true, completion: nil)
case .changed:
interactor.shouldFinish = progress > percentThreshold
interactor.update(progress)
case .cancelled:
interactor.hasStarted = false
interactor.cancel()
case .ended:
interactor.hasStarted = false
interactor.shouldFinish
? interactor.finish()
: interactor.cancel()
default:
break
}
}
/*
// 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.
}
*/
}
//
extension ProjectViewController: IGListAdapterDataSource {
func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] {
var items = [projectSelected!] as [IGListDiffable]
items += projectSelected!.updates as [IGListDiffable]
return items
}
func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController {
if object is Project {
return ProjectCoverSectionController()
} else {
return ProjectUpdateSectionController()
}
}
func emptyView(for listAdapter: IGListAdapter) -> UIView? {
return nil
}
}
extension ProjectViewController: ProjectCoverSectionControllerDelegate {
func closeTapped() {
// presentingViewController?.dismiss(animated: true, completion: nil)
self.performSegue(withIdentifier: "unwindToFeedSegue", sender: self)
}
func infoTapped() {
let projectInfoController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ProjectInfoViewController") as! ProjectInfoViewController
projectInfoController.projectSelected = projectSelected!
let navCon = UINavigationController(rootViewController: projectInfoController)
self.present(navCon, animated: true, completion: nil)
}
}
| ec7b2dc4f00b7bf32bc4ff9fcd41add3 | 32.661654 | 176 | 0.660934 | false | false | false | false |
aliceatlas/daybreak | refs/heads/master | Classes/SBURLField.swift | bsd-2-clause | 1 | /*
SBURLField.swift
Copyright (c) 2014, Alice Atlas
Copyright (c) 2010, Atsushi Jike
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import BLKGUI
let SBURLFieldRowCount = 3
let SBURLFieldMaxRowCount = 20
let SBURLFieldRowHeight: CGFloat = 20
let SBURLFieldRoundedCurve: CGFloat = SBFieldRoundedCurve
let SBURLFieldSheetPadding: CGFloat = 10
let kSBURLFieldSectionHeight: CGFloat = 18.0
struct SBURLFieldItem {
enum Type {
case None, Bookmark, History, GoogleSuggest
}
var type: Type
var title: String?
var URL: String?
var image: NSData?
static func None(title title: String, image: NSData?) -> SBURLFieldItem {
return SBURLFieldItem(type: .None, title: title, URL: nil, image: image)
}
static func Bookmark(title title: String?, URL: String, image: NSData?) -> SBURLFieldItem {
return SBURLFieldItem(type: .Bookmark, title: title, URL: URL, image: image)
}
static func History(URL URL: String, image: NSData?) -> SBURLFieldItem {
return SBURLFieldItem(type: .History, title: nil, URL: URL, image: image)
}
static func GoogleSuggest(title title: String, URL: String) -> SBURLFieldItem {
return SBURLFieldItem(type: .GoogleSuggest, title: title, URL: URL, image: nil)
}
}
@objc protocol SBURLFieldDelegate {
optional func URLFieldDidSelectBackward(_: SBURLField)
optional func URLFieldDidSelectForward(_: SBURLField)
optional func URLFieldShouldOpenURL(_: SBURLField)
optional func URLFieldShouldOpenURLInNewTab(_: SBURLField)
optional func URLFieldShouldDownloadURL(_: SBURLField)
optional func URLFieldTextDidChange(_: SBURLField)
optional func URLFieldWillResignFirstResponder(_: SBURLField)
}
@objc protocol SBURLFieldDatasource {
}
class SBURLField: SBView, NSTextFieldDelegate, NSTableViewDelegate, NSTableViewDataSource, SBAnswersIsFirstResponder {
private lazy var backwardButton: SBButton = {
let backwardRect = self.backwardRect
let backwardButton = SBButton(frame: backwardRect)
backwardButton.image = SBBackwardIconImage(backwardRect.size, true, false)
backwardButton.disableImage = SBBackwardIconImage(backwardRect.size, false, false)
backwardButton.backImage = SBBackwardIconImage(backwardRect.size, true, true)
backwardButton.backDisableImage = SBBackwardIconImage(backwardRect.size, false, true)
backwardButton.target = self
backwardButton.action = #selector(executeDidSelectBackward)
return backwardButton
}()
private lazy var forwardButton: SBButton = {
let forwardRect = self.forwardRect
let forwardButton = SBButton(frame: forwardRect)
forwardButton.image = SBForwardIconImage(forwardRect.size, true, false)
forwardButton.disableImage = SBForwardIconImage(forwardRect.size, false, false)
forwardButton.backImage = SBForwardIconImage(forwardRect.size, true, true)
forwardButton.backDisableImage = SBForwardIconImage(forwardRect.size, false, true)
forwardButton.target = self
forwardButton.action = #selector(executeDidSelectForward)
return forwardButton
}()
private lazy var imageView: SBURLImageView = {
let imageView = SBURLImageView(frame: self.imageRect)
imageView.imageFrameStyle = .None
return imageView
}()
private lazy var field: SBURLTextField = {
let field = SBURLTextField(frame: self.fieldRect)
field.target = self
field.action = #selector(executeShouldOpenURL)
field.commandAction = #selector(executeShouldOpenURLInNewTab)
field.optionAction = #selector(executeShouldDownloadURL)
field.bezeled = false
field.drawsBackground = false
field.bordered = false
field.focusRingType = .None
field.delegate = self
field.font = .systemFontOfSize(13.0)
field.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable]
field.cell!.wraps = false
field.cell!.scrollable = true
field.setRefusesFirstResponder(false)
return field
}()
private lazy var goButton: SBButton = {
let goRect = self.goRect
let goButton = SBButton(frame: goRect)
goButton.autoresizingMask = .ViewMinXMargin
goButton.image = SBGoIconImage(goRect.size, true, false)
goButton.disableImage = SBGoIconImage(goRect.size, false, false)
goButton.backImage = SBGoIconImage(goRect.size, true, true)
goButton.backDisableImage = SBGoIconImage(goRect.size, false, true)
goButton.target = self
goButton.action = #selector(go)
goButton.enabled = false
return goButton
}()
private lazy var sheet: SBURLFieldSheet = {
let sheet = SBURLFieldSheet(contentRect: self.appearedSheetRect, styleMask:(NSBorderlessWindowMask | NSNonactivatingPanelMask), backing: .Buffered, defer: true)
sheet.alphaValue = self.window!.alphaValue
sheet.opaque = false
sheet.backgroundColor = .clearColor()
sheet.hasShadow = false
sheet.contentView = self.contentView
return sheet
}()
private lazy var contentView: SBURLFieldContentView = {
var contentRect = NSZeroRect
contentRect.size = self.appearedSheetRect.size
return SBURLFieldContentView(frame: contentRect)
}()
var dataSource: SBURLFieldDatasource? {
didSet {
contentView.dataSource = dataSource !! self
}
}
var delegate: SBURLFieldDelegate? {
didSet {
contentView.delegate = delegate !! self
}
}
var image: NSImage? {
get { return imageView.image }
set(image) { imageView.image = image }
}
var stringValue: String! {
get { return field.stringValue }
set(inStringValue) {
let stringValue = inStringValue ?? ""
if stringValue != self.stringValue {
field.stringValue = stringValue
// Update go button
var hasScheme = false
goButton.enabled = !stringValue.isEmpty
goButton.title = goButton.enabled &? (stringValue.isURLString(&hasScheme) ? NSLocalizedString("Go", comment: "") : NSLocalizedString("Search", comment: ""))
}
}
}
var URLString: String {
get { return stringValue }
set(URLString) {
let editor = field.currentEditor() ?? window!.fieldEditor(true, forObject: field)!
var selectedRange = editor.selectedRange
var range = NSMakeRange(NSNotFound, 0)
let string = stringValue
let currentScheme = schemeForURLString(string)
let scheme = schemeForURLString(URLString)
if (scheme ?? "").hasPrefix(string) {
let headRange = (URLString as NSString).rangeOfString(string)
range.location = headRange.location + headRange.length
range.length = count(URLString) - range.location
} else {
let currentSchemeLength = count(currentScheme ?? "")
let schemeLength = count(scheme ?? "")
selectedRange.location -= currentSchemeLength
selectedRange.length -= currentSchemeLength
range.location = selectedRange.location + schemeLength
range.length = count(URLString) - range.location
}
self.stringValue = URLString
editor.selectedRange = range
}
}
var gsItems: [SBURLFieldItem] = []
var bmItems: [SBURLFieldItem] = []
var hItems: [SBURLFieldItem] = []
var items: [SBURLFieldItem] = [] {
didSet {
//!!! was setURLItems in original and this appears to not have been called anywhere
reloadData()
if items.isEmpty {
disappearSheet()
} else {
adjustSheet()
contentView.deselectRow()
}
}
}
var enabledBackward: Bool {
get { return backwardButton.enabled }
set(enabledBackward) { backwardButton.enabled = enabledBackward }
}
var enabledForward: Bool {
get { return forwardButton.enabled }
set(enabledForward) { forwardButton.enabled = enabledForward }
}
var enabledGo: Bool {
get { return goButton.enabled }
set(enabledGo) { goButton.enabled = enabledGo }
}
var hiddenGo: Bool {
get { return goButton.hidden }
set(hiddenGo) {
goButton.hidden = hidden
field.frame = fieldRect
}
}
private(set) var isOpenSheet = false
var editing: Bool { return true }
var isFirstResponder: Bool {
return window &! {$0.firstResponder === field.currentEditor()}
}
var placeholderString: String? {
get { return field.cell!.placeholderString }
set(placeholderString) { field.cell!.placeholderString = placeholderString }
}
var textColor: NSColor? {
get { return field.textColor }
set(textColor) { field.textColor = textColor }
}
override var nextKeyView: NSView? {
get { return field.nextKeyView }
set(nextKeyView) { field.nextKeyView = nextKeyView }
}
override init(frame: NSRect) {
var r = frame
r.size.width.constrain(min: minimumSize.width)
r.size.height.constrain(min: minimumSize.height)
super.init(frame: r)
addSubviews(backwardButton, forwardButton, imageView, field, goButton)
hiddenGo = true
}
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
let minimumSize = NSMakeSize(100.0, 22.0)
var font: NSFont? { return field.font }
var sheetHeight: CGFloat {
let rowCount = items.count.constrained(max: SBURLFieldMaxRowCount)
return SBURLFieldRowHeight * CGFloat(rowCount) + SBURLFieldSheetPadding * 2
}
var appearedSheetRect: NSRect {
var r = NSZeroRect
r.size.width = bounds.size.width - buttonWidth * 2 - goButtonWidth
r.size.height = sheetHeight
let position = (window?.toolbar as? SBToolbar)?.itemRectInScreenForIdentifier(kSBToolbarURLFieldItemIdentifier).origin ?? .zero
r.origin.x = frame.origin.x + position.x
r.origin.y = frame.origin.y + position.y
r.origin.x += buttonWidth * 2
r.origin.y -= r.size.height - 1
return r
}
// MARK: Rects
let buttonWidth: CGFloat = 27.0
let goButtonWidth: CGFloat = 75.0
let imageWidth: CGFloat = 20.0
var backwardRect: NSRect {
return NSMakeRect(0, 0, buttonWidth, bounds.size.height)
}
var forwardRect: NSRect {
return NSMakeRect(buttonWidth, 0, buttonWidth, bounds.size.height)
}
var imageRect: NSRect {
let w: CGFloat = 16.0
return NSMakeRect(
buttonWidth * 2 + (imageWidth - w) / 2,
(bounds.size.height - w) / 2,
w, w)
}
var fieldRect: NSRect {
var r = NSZeroRect
r.size.width = bounds.size.width - imageWidth - 4.0 - buttonWidth * 2 - (!goButton.hidden ? goButtonWidth : 0)
r.size.height = bounds.size.height - 2
r.origin.x = buttonWidth * 2 + imageWidth
r.origin.y = -2.0
return r
}
var goRect: NSRect {
return NSMakeRect(bounds.size.width - goButtonWidth, 0, goButtonWidth, bounds.size.height)
}
// MARK: Construction
func tableViewDidSingleAction(tableView: NSTableView) {
let rowIndex = tableView.selectedRow
if rowIndex > -1 && canSelectIndex(rowIndex) {
contentView.pushSelectedItem()
disappearSheet()
NSApp.sendAction(field.action, to: field.target, from: field)
}
}
func canSelectIndex(index: Int) -> Bool {
var can = false
var matchIndex = false
switch (gsItems.isEmpty, bmItems.isEmpty, hItems.isEmpty) {
case (false, true, true), (true, false, true), (true, true, false):
matchIndex = index == 0
case (false, false, true):
matchIndex = (index == 0) || (index == gsItems.count)
case (true, false, false):
matchIndex = (index == 0) || (index == bmItems.count)
case (false, true, false):
matchIndex = (index == 0) || (index == gsItems.count)
case (false, false, false):
matchIndex = (index == 0) || (index == gsItems.count) || (index == gsItems.count + bmItems.count)
case (true, true, true):
break
}
return !matchIndex
}
// MARK: Delegate
func tableViewSelectionDidChange(notification: NSNotification) {
let rowIndex = (notification.object as! NSTableView).selectedRow
if rowIndex > -1 && canSelectIndex(rowIndex) {
contentView.pushSelectedItem()
}
}
func tableViewSelectionIsChanging(notification: NSNotification) {
contentView.needsDisplay = true // Keep drawing background
}
func tableView(tableView: NSTableView, shouldSelectRow rowIndex: Int) -> Bool {
return canSelectIndex(rowIndex)
}
func tableView(tableView: NSTableView, selectionIndexesForProposedSelection proposedSelectionIndexes: NSIndexSet) -> NSIndexSet {
let index = proposedSelectionIndexes.firstIndex // because single selection
if canSelectIndex(index) {
return proposedSelectionIndexes
}
return NSIndexSet()
}
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return kSBURLFieldSectionHeight
}
override func controlTextDidBeginEditing(notification: NSNotification) {
// Show go button
hiddenGo = false
updateGoTitle(NSApp.currentEvent)
}
override func controlTextDidChange(notification: NSNotification) {
let currentEvent = NSApp.currentEvent!
let characters: NSString = currentEvent.characters!
let character = Int(characters.characterAtIndex(0))
let stringValue = field.stringValue
var hasScheme = false
// Update go button
hiddenGo = false
goButton.enabled = !stringValue.isEmpty
goButton.title = goButton.enabled &? (stringValue.isURLString(&hasScheme) ? NSLocalizedString("Go", comment: "") : NSLocalizedString("Search", comment: ""))
if (character == NSDeleteCharacter ||
character == NSBackspaceCharacter ||
character == NSLeftArrowFunctionKey ||
character == NSRightArrowFunctionKey) {
// Disappear sheet
if isOpenSheet {
disappearSheet()
}
} else {
// Get items from Bookmarks and History items
executeTextDidChange()
appearSheetIfNeeded(false)
}
}
override func controlTextDidEndEditing(notification: NSNotification) {
// Hide go button
hiddenGo = true
// Disappear sheet
if isOpenSheet {
disappearSheet()
}
let currentEvent = window!.currentEvent!
if currentEvent.type == .KeyDown {
let characters: NSString = currentEvent.characters!
let character = Int(characters.characterAtIndex(0))
if character == NSTabCharacter { // Tab
// If the user push Tab key, make first responder to next responder
window!.makeFirstResponder(field.nextKeyView)
}
}
}
func control(control: NSControl, textView: NSTextView, doCommandBySelector commandSelector: Selector) -> Bool {
if control === field &&
commandSelector == #selector(insertNewlineIgnoringFieldEditor(_:)) {
// Ignore new line action
let center = NSNotificationCenter.defaultCenter()
center.postNotificationName(NSControlTextDidEndEditingNotification, object: self)
field.sendAction(field.optionAction, to: field.target)
return true
}
return false
}
// MARK: DataSource
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return items.count
}
func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row rowIndex: Int) -> AnyObject? {
if tableColumn?.identifier == kSBURL, let item = items.get(rowIndex) {
switch item.type {
case .None: return item.title
case .GoogleSuggest: return item.title
case .Bookmark, .History: return item.title ?? item.URL
}
}
return nil
}
func tableView(tableView: NSTableView, willDisplayCell cell: AnyObject, forTableColumn tableColumn: NSTableColumn?, row rowIndex: Int) {
if tableColumn?.identifier != kSBURL { return }
if let item = items.get(rowIndex), cell = cell as? SBURLFieldDataCell {
var string: String?
var image: NSImage?
var separator = false
var sectionHeader = false
var drawsImage = true
switch item.type {
case .None:
if let data = item.image {
image = NSImage(data: data)
image!.size = NSMakeSize(16.0, 16.0)
}
string = item.title
separator = rowIndex > 0
sectionHeader = true
case .GoogleSuggest:
string = item.title
drawsImage = false
case .History, .Bookmark:
if let data = item.image {
image = NSImage(data: data)
image!.size = NSMakeSize(16.0, 16.0)
}
string = item.title ?? item.URL
}
cell.separator = separator
cell.sectionHeader = sectionHeader
cell.drawsImage = drawsImage
cell.image = image
string !! { cell.objectValue = $0 }
}
}
// MARK: Action
func endEditing() {
disappearSheet()
hiddenGo = true
field.cell!.endEditing(window!.fieldEditor(false, forObject: field)!)
}
func adjustSheet() {
let sheetRect = appearedSheetRect
sheet.setFrame(sheetRect, display: true)
sheet.alphaValue = window!.alphaValue
contentView.adjustTable()
}
func appearSheetIfNeeded(closable: Bool) {
if !items.isEmpty {
if !isOpenSheet {
appearSheet()
}
reloadData()
adjustSheet()
contentView.deselectRow()
} else if closable {
disappearSheet()
}
}
func appearSheet() {
if !sheet.visible {
adjustSheet()
window!.addChildWindow(sheet, ordered: .Above)
contentView.deselectRow()
sheet.orderFront(nil)
isOpenSheet = true
needsDisplay = true
contentView.needsDisplay = true
}
}
func disappearSheet() {
if sheet.visible {
window!.removeChildWindow(sheet)
needsDisplay = true
sheet.orderOut(nil)
isOpenSheet = false
needsDisplay = true
}
}
func selectRowAbove() {
var rowIndex = contentView.selectedRowIndex
do {
rowIndex--
} while !canSelectIndex(rowIndex)
if rowIndex < 1 {
rowIndex = items.count - 1
}
contentView.selectRow(rowIndex)
}
func selectRowBelow() {
var rowIndex = contentView.selectedRowIndex
do {
rowIndex++
} while !canSelectIndex(rowIndex)
if rowIndex >= items.count {
rowIndex = 1
}
contentView.selectRow(rowIndex)
}
func reloadData() {
adjustSheet()
contentView.reloadData()
}
func selectText(sender: AnyObject?) {
field.selectText(sender)
}
func updateGoTitle(event: NSEvent?) {
let modifierFlags = event?.modifierFlags ?? []
if modifierFlags.contains(.CommandKeyMask) {
goButton.title = NSLocalizedString("Open", comment: "")
} else if modifierFlags.contains(.AlternateKeyMask) {
goButton.title = NSLocalizedString("Download", comment: "")
} else {
var hasScheme = false
let title = stringValue.ifNotEmpty !! { $0.isURLString(&hasScheme) ? NSLocalizedString("Go", comment: "") : NSLocalizedString("Search", comment: "") }
goButton.title = title
}
}
func go() {
let modifierFlags = NSApp.currentEvent?.modifierFlags ?? []
if modifierFlags.contains(.CommandKeyMask) {
executeShouldOpenURLInNewTab()
} else if modifierFlags.contains(.AlternateKeyMask) {
executeShouldDownloadURL()
} else {
executeShouldOpenURL()
}
}
// MARK: Exec
func executeDidSelectBackward() {
delegate?.URLFieldDidSelectBackward?(self)
}
func executeDidSelectForward() {
delegate?.URLFieldDidSelectForward?(self)
}
func executeShouldOpenURL() {
delegate?.URLFieldShouldOpenURL?(self)
}
func executeShouldOpenURLInNewTab() {
delegate?.URLFieldShouldOpenURLInNewTab?(self)
}
func executeShouldDownloadURL() {
delegate?.URLFieldShouldDownloadURL?(self)
}
func executeTextDidChange() {
delegate?.URLFieldTextDidChange?(self)
}
func executeWillResignFirstResponder() {
delegate?.URLFieldWillResignFirstResponder?(self)
}
// MARK: Drawing
override func drawRect(rect: NSRect) {
var r = bounds
var path = SBRoundedPath(r, SBURLFieldRoundedCurve, 0, true, true)
NSColor.whiteColor().set()
path.fill()
r.origin.x += 0.5
r.origin.y += 3.0
if r.size.width >= 1.0 {
r.size.width -= 1.0
}
if r.size.height >= 4.5 {
r.size.height -= 4.5
}
path = SBRoundedPath(r, SBURLFieldRoundedCurve, 0, true, false)
path.lineWidth = 1.0
NSColor(calibratedWhite: 0.75, alpha: 1.0).set()
path.stroke()
r = bounds
r.origin.x += 0.5
r.origin.y += 0.5
r.size.width -= 1.0
r.size.height -= 1.0
path = SBRoundedPath(r, SBURLFieldRoundedCurve, 0, true, true)
path.lineWidth = 0.5
NSColor.blackColor().set()
path.stroke()
}
override func resizeWithOldSuperviewSize(oldBoundsSize: NSSize) {
if isOpenSheet {
disappearSheet()
}
super.resizeWithOldSuperviewSize(oldBoundsSize)
}
override func resizeSubviewsWithOldSize(oldBoundsSize: NSSize) {
if isOpenSheet {
disappearSheet()
}
super.resizeSubviewsWithOldSize(oldBoundsSize)
}
}
class SBURLImageView: NSImageView, NSDraggingSource {
var field: SBURLField { return superview as! SBURLField }
var URL: NSURL { return NSURL(string: field.stringValue)! }
var selectedWebViewImageForBookmark: NSImage? {
return (field.delegate as? SBDocument)?.selectedWebViewImageForBookmark
}
var selectedWebViewImageDataForBookmark: NSData? {
return (field.delegate as? SBDocument)?.selectedWebViewImageDataForBookmark
}
var dragImage: NSImage {
let URLString: NSString = URL.absoluteString
let margin: CGFloat = 5.0
let attribute: [String: AnyObject] = [NSFontAttributeName: field.font!]
let textSize = URLString.sizeWithAttributes(attribute)
var size = bounds.size
size.width += textSize.width + margin
var imageRect = NSRect(size: bounds.size)
imageRect.origin.x = (size.height - imageRect.size.width) / 2
imageRect.origin.y = (size.height - imageRect.size.height) / 2
let textRect = NSMakeRect(margin + imageRect.maxX, 0, textSize.width, size.height)
return NSImage(size: size) {
self.image?.drawInRect(imageRect, fromRect: .zero, operation: .CompositeSourceOver, fraction: 1.0)
URLString.drawInRect(textRect, withAttributes: attribute)
}
}
override func mouseDown(event: NSEvent) {
//!!!@autoreleasepool {
let point = convertPoint(event.locationInWindow, fromView: nil)
while true {
let mask: NSEventMask = [.LeftMouseDraggedMask, .LeftMouseUpMask]
let newEvent = window!.nextEventMatchingMask(Int(mask.rawValue))!
let newPoint = convertPoint(newEvent.locationInWindow, fromView: nil)
var isDragging = false
if bounds.contains(newPoint) {
if newEvent.type == .LeftMouseUp {
mouseUpActionWithEvent(event)
break
} else if newEvent.type == .LeftMouseDragged {
isDragging = true
}
} else {
if newEvent.type == .LeftMouseDragged {
isDragging = true
}
}
if isDragging {
let delta = NSMakePoint(point.x - newPoint.x, point.y - newPoint.y)
if delta.x >= 5 || delta.x <= -5 || delta.y >= 5 || delta.y <= -5 {
mouseDraggedActionWithEvent(event)
break
}
}
}
//}
}
func mouseDraggedActionWithEvent(event: NSEvent) {
var item = NSDraggingItem(pasteboardWriter: URL)
let imageFrame = NSRect(origin: bounds.origin, size: dragImage.size)
item.setDraggingFrame(imageFrame, contents: dragImage)
let session = beginDraggingSessionWithItems([item], event: event, source: self)
session.animatesToStartingPositionsOnCancelOrFail = true
session.draggingFormation = .None
window!.title !! { session.draggingPasteboard.setString($0, forType: NSPasteboardTypeString) }
selectedWebViewImageForBookmark?.TIFFRepresentation !! { session.draggingPasteboard.setData($0, forType: NSPasteboardTypeTIFF) }
}
func draggingSession(session: NSDraggingSession, sourceOperationMaskForDraggingContext context: NSDraggingContext) -> NSDragOperation {
return .Copy
}
func mouseUpActionWithEvent(event: NSEvent) {
field.selectText(self)
}
}
class SBURLTextField: NSTextField {
var commandAction: Selector = nil
var optionAction: Selector = nil
var field: SBURLField { return superview as! SBURLField }
// MARK: Responder
override var acceptsFirstResponder: Bool { return true }
override func becomeFirstResponder() -> Bool {
selectText(nil)
return true
}
override func resignFirstResponder() -> Bool {
field.disappearSheet()
field.executeWillResignFirstResponder()
return true
}
override func selectText(sender: AnyObject?) {
super.selectText(nil)
// self through NSControlTextDidBeginEditingNotification
NSNotificationCenter.defaultCenter().postNotificationName(NSControlTextDidBeginEditingNotification, object: self)
}
override func flagsChanged(event: NSEvent) {
field.updateGoTitle(event)
}
// MARK: Event
override func performKeyEquivalent(event: NSEvent) -> Bool {
let center = NSNotificationCenter.defaultCenter()
let character = (event.characters as NSString?)?.characterAtIndex(0) !! {Int($0)}
if character == NSCarriageReturnCharacter || character == NSEnterCharacter {
if event.modifierFlags.contains(.CommandKeyMask) {
// Command + Return
center.postNotificationName(NSControlTextDidEndEditingNotification, object: self)
sendAction(commandAction, to: target)
return true
}
} else if field.isOpenSheet && event.type == .KeyDown, let character = character {
switch character {
case NSUpArrowFunctionKey:
field.selectRowAbove()
return true
case NSDownArrowFunctionKey:
field.selectRowBelow()
return true
case NSLeftArrowFunctionKey:
center.postNotificationName(NSControlTextDidChangeNotification, object: self)
case NSRightArrowFunctionKey:
center.postNotificationName(NSControlTextDidChangeNotification, object: self)
case 0x1B:
field.disappearSheet()
default:
break
}
}
return super.performKeyEquivalent(event)
}
}
class SBURLFieldSheet: NSPanel {
override var acceptsFirstResponder: Bool { return true }
override func becomeFirstResponder() -> Bool { return true }
override func resignFirstResponder() -> Bool { return true }
//override var acceptsMouseMovedEvents: Bool { return true }
override init(contentRect: NSRect, styleMask windowStyle: Int, backing bufferingType: NSBackingStoreType, defer deferCreation: Bool) {
super.init(contentRect: contentRect, styleMask: windowStyle, backing: bufferingType, defer: deferCreation)
acceptsMouseMovedEvents = true
}
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
/*override func performKeyEquivalent(event: NSEvent) -> Bool {
return super.performKeyEquivalent(event)
}*/
}
class SBURLFieldContentView: NSView {
var dataSource: NSTableViewDataSource? {
get { return table.dataSource() }
set(dataSource) { table.setDataSource(dataSource) }
}
var delegate: NSTableViewDelegate? {
get { return table.delegate() }
set(delegate) { table.setDelegate(delegate) }
}
var field: SBURLField? {
if let tableDelegate = table.delegate() as? SBURLField {
return tableDelegate
}
return nil
}
var selectedRowIndex: Int { return table.selectedRow }
//private var text: NSTextField
private var scrollerRect: NSRect {
var r = NSZeroRect
r.origin.x = 1
r.size.width = bounds.size.width - 2
r.size.height = SBURLFieldRowHeight * CGFloat(SBURLFieldRowCount)
r.origin.y = bounds.size.height - r.size.height
return r
}
private lazy var scroller: NSScrollView = {
let scroller = BLKGUI.ScrollView(frame: self.scrollerRect)
scroller.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable]
scroller.autohidesScrollers = true
scroller.hasVerticalScroller = true
scroller.autohidesScrollers = true
scroller.backgroundColor = SBTableLightGrayCellColor
scroller.drawsBackground = true
scroller.documentView = self.table
return scroller
}()
private lazy var table: NSTableView = {
var tableRect = NSRect(size: self.scrollerRect.size)
let cell = SBURLFieldDataCell()
cell.font = .systemFontOfSize(12.0)
cell.alignment = .Left
let column = NSTableColumn(identifier: kSBURL)
column.dataCell = cell
column.editable = false
column.width = self.bounds.size.width
let table = NSTableView(frame: tableRect)
table.backgroundColor = .clearColor()
table.rowHeight = SBURLFieldRowHeight - 2
table.addTableColumn(column)
table.allowsMultipleSelection = false
table.allowsColumnSelection = false
table.allowsEmptySelection = true
table.action = #selector(SBURLField.tableViewDidSingleAction(_:))
table.columnAutoresizingStyle = .LastColumnOnlyAutoresizingStyle
table.headerView = nil
table.cornerView = nil
table.autoresizingMask = .ViewWidthSizable
table.intercellSpacing = NSZeroSize
return table
}()
override init(frame: NSRect) {
super.init(frame: frame)
addSubview(scroller)
}
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
// MARK: Action
func adjustTable() {
var scrollerRect = scroller.frame
var tableRect = table.frame
let numberOfRows = dataSource?.numberOfRowsInTableView?(table) ?? 0
let rowCount = numberOfRows.constrained(max: SBURLFieldMaxRowCount)
scrollerRect.size.width = bounds.size.width - 2
scrollerRect.size.height = SBURLFieldRowHeight * CGFloat(rowCount)
scrollerRect.origin.y = SBURLFieldSheetPadding
tableRect.size.width = scrollerRect.size.width
scroller.frame = scrollerRect
table.frame = tableRect
}
func selectRow(rowIndex: Int) -> Bool {
table.selectRowIndexes(NSIndexSet(index: rowIndex), byExtendingSelection: false)
table.scrollRowToVisible(rowIndex)
return pushItemAtIndex(rowIndex)
}
func deselectRow() {
table.deselectAll(nil)
table.scrollRowToVisible(0)
field!.image = nil
}
func reloadData() {
table.reloadData()
}
func pushSelectedItem() {
pushItemAtIndex(table.selectedRow)
}
func pushItemAtIndex(index: Int) -> Bool {
if let field = field, selectedItem = field.items.get(index) {
switch selectedItem.type {
case .GoogleSuggest:
field.URLString = selectedItem.title!
return true
default:
let URLString = selectedItem.URL!
if URLString != field.stringValue {
selectedItem.image !! {NSImage(data: $0)} !! {field.image = $0}
field.URLString = URLString
return true
}
}
}
return false
}
// MARK: Drawing
override func drawRect(rect: NSRect) {
let b = bounds
var path = SBRoundedPath(b, SBURLFieldRoundedCurve, 0, false, true)
let locations: [CGFloat] = [0.0,
SBURLFieldSheetPadding / b.size.height,
(b.size.height - SBURLFieldSheetPadding) / b.size.height,
1.0]
let colors = [SBTableGrayCellColor, SBTableLightGrayCellColor, SBTableLightGrayCellColor, .whiteColor()]
let gradient = NSGradient(colors: colors, atLocations: locations, colorSpace: .genericRGBColorSpace())! //!!! device?
gradient.drawInRect(b, angle: 90)
var r = b
r.origin.x += 0.5
r.origin.y += 0.5
if r.size.width >= 1.0 {
r.size.width -= 1.0
}
path = SBRoundedPath(r, SBURLFieldRoundedCurve, 0, false, true)
path.lineWidth = 0.5
NSColor.blackColor().set()
path.stroke()
}
}
private class SBURLFieldDataCell: NSCell {
var separator = false
var sectionHeader = false
var drawsImage = true
func setDefaultValues() {
alignment = .Left
}
@objc(initImageCell:)
override init(imageCell anImage: NSImage?) {
super.init(imageCell: anImage)
setDefaultValues()
}
@objc(initTextCell:)
override init(textCell aString: String) {
super.init(textCell: aString)
setDefaultValues()
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
let side: CGFloat = 5.0
var leftMargin: CGFloat { return sectionHeader ? 0.0 : 15.0 }
var imageWidth: CGFloat { return drawsImage ? 20.0 : 0.0 }
override func drawWithFrame(cellFrame: NSRect, inView controlView: NSView) {
drawInteriorWithFrame(cellFrame, inView: controlView)
drawImageWithFrame(cellFrame, inView: controlView)
drawTitleWithFrame(cellFrame, inView: controlView)
}
override func drawInteriorWithFrame(cellFrame: NSRect, inView controlView: NSView) {
let leftMargin = side + self.leftMargin
var r = cellFrame
r.origin.x += leftMargin
r.size.width -= leftMargin
let selectedColor = NSColor.alternateSelectedControlColor().colorUsingColorSpace(.genericRGBColorSpace())
let backgroundColor = SBBackgroundLightGrayColor
let cellColor = SBTableLightGrayCellColor
backgroundColor.set()
NSRectFill(r)
cellColor.set()
NSRectFill(cellFrame)
if highlighted {
let r = cellFrame
let path = SBRoundedPath(NSInsetRect(r, 1.0, 1.0), (r.size.height - 1.0 * 2) / 2, 0.0, true, true)
let gradient = NSGradient(startingColor: SBAlternateSelectedLightControlColor,
endingColor: SBAlternateSelectedControlColor)!
SBPreserveGraphicsState {
path.addClip()
gradient.drawInRect(r, angle: 90)
}
}
}
func drawImageWithFrame(cellFrame: NSRect, inView controlView: NSView) {
if let image = image {
var r = NSRect(origin: cellFrame.origin, size: image.size)
r.origin.x += side + leftMargin + (imageWidth - r.size.width) / 2
r.origin.y += (cellFrame.size.height - r.size.height) / 2
image.drawInRect(r, operation: .CompositeSourceOver, fraction: 1.0, respectFlipped: true)
}
}
func drawTitleWithFrame(cellFrame: NSRect, inView controlView: NSView) {
let title = self.title as String?
if let title: NSString = title?.ifNotEmpty {
let imageWidth = self.imageWidth + side + leftMargin
let titleRect = NSMakeRect(cellFrame.origin.x + imageWidth, cellFrame.origin.y, cellFrame.size.width - imageWidth, cellFrame.size.height)
let textColor = (sectionHeader ? SBTableDarkGrayCellColor : .blackColor()).colorUsingColorSpace(.genericRGBColorSpace())!
let sTextColor: NSColor = highlighted ? .clearColor() : .whiteColor()
let color = highlighted ? .whiteColor() : textColor
let font = NSFont.systemFontOfSize(sectionHeader ? 11.0 : 12.0)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .ByTruncatingTail
let attribute = [NSFontAttributeName: font, NSForegroundColorAttributeName: color, NSParagraphStyleAttributeName: paragraphStyle]
let sAttribute = [NSFontAttributeName: font, NSForegroundColorAttributeName: sTextColor, NSParagraphStyleAttributeName: paragraphStyle]
var size = title.sizeWithAttributes(attribute)
size.width.constrain(max: titleRect.size.width - side * 2)
var r = NSRect(size: size)
switch alignment {
case .Left:
r.origin.x = titleRect.origin.x + side
case .Right:
r.origin.x = titleRect.origin.x + side + ((titleRect.size.width - side * 2) - size.width)
case .Center:
r.origin.x = titleRect.origin.x + ((titleRect.size.width - side * 2) - size.width) / 2
default:
break
}
r.origin.y = titleRect.origin.y + (titleRect.size.height - r.size.height) / 2
var sr = r
sr.origin.y += 1.0
title.drawInRect(sr, withAttributes: sAttribute)
title.drawInRect(r, withAttributes: attribute)
if separator {
let leftMargin = r.maxX + 10.0
var separatorRect = NSMakeRect(cellFrame.origin.x + leftMargin, r.midY, cellFrame.size.width - leftMargin, 1.0)
NSColor.whiteColor().set()
NSRectFill(separatorRect)
separatorRect.origin.y -= 1.0
SBTableGrayCellColor.set()
NSRectFill(separatorRect)
}
}
}
}
func schemeForURLString(URLString: String) -> String? {
if let range = URLString.rangeOfString("://") {
return URLString[URLString.startIndex..<range.endIndex]
}
return nil
} | 9e03cddaee38007e50c821f521ef9f80 | 35.629437 | 172 | 0.611899 | false | false | false | false |
Subsets and Splits